问题是这样的,使用HTPP发送请求的时候,写了一个Post方法:
public static String postRequest(String url, String request, int timeout) {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpPost post = new HttpPost(url);
String res = null;
try {
StringEntity s = new StringEntity(request);
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
//设置请求参数
post.setEntity(s);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//返回json格式
res = EntityUtils.toString(response.getEntity());
return res;
}else {
res = EntityUtils.toString(response.getEntity());
}
}catch (ConnectTimeoutException e) {
//e.printStackTrace();
} catch (SocketTimeoutException e) {
//e.printStackTrace();
} catch (ConnectException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
//e.printStackTrace();
}
}
}
return res;
}
以前都是好好的,什么汉语,日语,中文啥的都是正常的,但是内容为西班牙语的时候出现了乱码。
原文如下:
El código de verificación de su teléfono móvil es:56:56
经过以上的post方法发送,最后的内容变成这样:
El c�digo de verificaci�n de su tel�fono m�vil es:56:60
西班牙语中的特殊符号都乱码了,但是明明已经设置了内容的编码格式为UTF-8
s.setContentEncoding("UTF-8")
然后debug调试的时候,看见contentType的charset还是unicode编码,所以我又在contentType中设置编码为UTF-8,但是最后还是乱码。这就很奇怪了噢,难道不支持UTF-8🤔?这样一想,干脆就不设置他的编码格式算了,可结果还是乱码了😳。
最后只能一步步的走下去,发现StringEntity的处理逻辑如下:
public StringEntity(String string) throws UnsupportedEncodingException {
this(string, ContentType.DEFAULT_TEXT);
}
public StringEntity(String string, ContentType contentType) throws UnsupportedCharsetException {
Args.notNull(string, "Source string");
Charset charset = contentType != null ? contentType.getCharset() : null;
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
this.content = string.getBytes(charset);
if (contentType != null) {
this.setContentType(contentType.toString());
}
}
当不传入ContentType时,会使用默认值,而该处的默认编码格式是:ISO_5598_1。所以最终还是乱码的😔
最后我在初始化的时候指定编码为UTF-8之后,果然好了。
StringEntity s = new StringEntity(request, StandardCharsets.UTF_8);