记录使用StringEntity编码格式化乱码的经历

问题是这样的,使用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);
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值