在調用後臺接口時,發現傳過去的json串中的中文字符是亂碼,特此記錄下:
原來老的代碼
public static String doPostJson(String url, Map<String, String> headers, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.addHeader(key, headers.get(key));
}
}
httpPost.setHeader("HTTP Method", "POST");
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity = new StringEntity(json);
entity.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.error("doPost, error:", e.toString());
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("doPost, error:", e.toString());
}
}
return resultString;
}
修改過之後的代碼
public static String doPostJson(String url, Map<String, String> headers, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.addHeader(key, headers.get(key));
}
}
httpPost.setHeader("HTTP Method", "POST");
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//!!!!!這裏改了!!!!!!
StringEntity entity = new StringEntity(json,"UTF-8");
entity.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.error("doPost, error:", e.toString());
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("doPost, error:", e.toString());
}
}
return resultString;
}
關於編碼問題,發現一篇博客講的很透徹:
深入分析 Java 中的中文編碼問題