一:前言
這篇文章主要是講給需要用百度翻譯api做產品的人,下面肯定不會將怎麼申請百度翻譯api,怎麼用,因爲這一些你在網上搜(百度等等)是有很多的,主要我是講在用百度翻譯api的時候,怎麼讓java使用post請求去請求百度翻譯的接口,從而避免get請求帶來的414和返回null
二:場景模擬
公司產品準備上線了,翻譯這一模塊是直接用百度翻譯提供的api的demo直接用,用戶某一天用一個超長的文本去翻譯,發現返回值爲null,查看後臺才知道是請求出錯414url地址過長,然後第一時間就想到不能get請求,要用post請求,當我去百度或者其他的搜索引擎去搜結果的時候,發現用java的post請求去請求百度翻譯api的寥寥無幾。就準備自己琢磨去修改一下代碼
三:步驟分析
首先我們下載的demo有這三個核心文件,一個是負責請求的,一個負責加密,一個負者業務處理。
所以我們需要在HttpGet.java去增加一個post請求
步驟一:在HttpGet中增加一個post請求,當然這個你也可以自己去寫一個類HttpPost來寫post請求,這裏是直接在HttpGet.java中增加的post
1.post方法:主要是負責post請求,包括傳遞參數。
2.convertStreamToString方法:主要是對post請求返回的結果進行處理,轉換爲一個String對象
步驟二:編寫post方法,參數url主要是請求地址,param主要是需要傳遞的參數,我是一個map,你們自己可以爲String或者其他的,這裏主要是明白一下幾點
1.
httpURLConnection.setDoOutput(true);//此申明在申明請求方式爲post之前
httpURLConnection.setRequestMethod("POST");//申明請求爲post
2.
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//後面的application/x-www-form-urlencoded主要能我們傳遞參數的時候爲name=jc&age=54&sex=2這種get形式來傳遞參數
httpURLConnection.setRequestProperty("Content-Length", String.valueOf("5000"));//設置傳遞文件的長度
3.
outputStreamWriter.write(builder.toString());主要這裏是向請求地址去傳遞參數
步驟三:編寫convertStreamToString,主要一個參數就是inputStream,輸入流,來解析結果
四:HttpGet.java完整代碼
package cn.cigit.contextquery.servlet;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
class HttpGet {
protected static final int SOCKET_TIMEOUT = 10000; // 10S
protected static final String GET = "GET";
protected static final String POST = "POST";
public static String get(String host, Map<String, String> params) {
try {
System.out.println("開始處理");
// 設置SSLContext
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
String sendUrl = getUrlWithQueryString(host, params);
// System.out.println("URL:" + sendUrl);
URL uri = new URL(sendUrl); // 創建URL對象
URLConnection urlConnection=uri.openConnection();
HttpURLConnection conn = (HttpURLConnection)urlConnection;
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
}
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf("1532"));
conn.setConnectTimeout(10000);
conn.setDoInput(true);
int statusCode = conn.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
System.out.println("Http錯誤碼:" + statusCode);
}
// 讀取服務器的數據
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
builder.append(line);
}
String text = builder.toString();
close(br); // 關閉數據流
close(is); // 關閉數據流
conn.disconnect(); // 斷開連接
return text;
} catch (MalformedURLException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
} catch (KeyManagementException e) {
System.out.println(e.toString());
} catch (NoSuchAlgorithmException e) {
System.out.println(e.toString());
}
return null;
}
public static String getUrlWithQueryString(String url, Map<String, String> params) {
if (params == null) {
return url;
}
StringBuilder builder = new StringBuilder(url);
if (url.contains("?")) {
builder.append("&");
} else {
builder.append("?");
}
int i = 0;
for (String key : params.keySet()) {
String value = params.get(key);
if (value == null) { // 過濾空的key
continue;
}
if (i != 0) {
builder.append('&');
}
builder.append(key);
builder.append('=');
builder.append(encode(value));
i++;
}
return builder.toString();
}
protected static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String encode(String input) {
if (input == null) {
return "";
}
try {
return URLEncoder.encode(input, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return input;
}
private static TrustManager myX509TrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
public static String post(String url, Map<String,String> param) throws Exception {
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf("5000"));
httpURLConnection.setConnectTimeout(10000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
String resultBuffer = "";
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
int i = 0;
StringBuilder builder = new StringBuilder();
for (String key : param.keySet()) {
String value = param.get(key);
if (value == null) { // 過濾空的key
continue;
}
if (i != 0) {
builder.append('&');
}
builder.append(key);
builder.append('=');
builder.append(encode(value));
i++;
}
outputStreamWriter.write(builder.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
resultBuffer = convertStreamToString(inputStream);
System.out.println(resultBuffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer;
}
public static String convertStreamToString(InputStream is) {
StringBuilder sb1 = new StringBuilder();
byte[] bytes = new byte[4096];
int size = 0;
try {
while ((size = is.read(bytes)) > 0) {
String str = new String(bytes, 0, size, "UTF-8");
sb1.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb1.toString();
}
}
注意你可能需要修改的地方,post請求中的param參數的類型,主要我是一個map數據,你可能是String,但是裏面組裝數據也需要修改。還有就是TransApi.java中把
HttpGet.get(TRANS_API_HOST, params);改爲HttpGet.post(TRANS_API_HOST, params);
基本到這裏就結束了,不懂的小夥伴可以加我微信:y958231955
886~