发送http请求时中文乱码
刚开始发送http请求时,中文传输的字段一直是乱码,找不到问题,后来查阅资料后才知道设置UTF-8有可能失败,需要在StringEntity处设置
原来代码
/**
* 发https请求,json做参数
*
* @param url url
* @param map json参数
* @return result
*/
public static String HttpsPostSendJson(String url, String map) {
String result = null;
try {
//HttpClient httpClient = new SSLClient();
HttpPost httpPost = new HttpPost(url);
//设置参数
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(map);
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(REQUEST_TIMEOUT)
.setConnectTimeout(REQUEST_TIMEOUT)
.build();
httpPost.setConfig(config);
httpPost.setEntity(stringEntity);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(createSSLConnSocketFactory())
.setDefaultRequestConfig(config)
.build();
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
return result;
}
更改后代码
/**
* 发https请求,json做参数
*
* @param url url
* @param map json参数
* @return result
*/
public static String HttpsPostSendJson(String url, String map) {
String result = null;
try {
//HttpClient httpClient = new SSLClient();
HttpPost httpPost = new HttpPost(url);
//设置参数
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(map,"UTF-8");
//stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(REQUEST_TIMEOUT)
.setConnectTimeout(REQUEST_TIMEOUT)
.build();
httpPost.setConfig(config);
httpPost.setEntity(stringEntity);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(createSSLConnSocketFactory())
.setDefaultRequestConfig(config)
.build();
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
return result;
}
经测试,发送中文不再显示乱码.
本文来自博客园,作者:xiaolifc,转载请注明原文链接:https://www.cnblogs.com/xiaolibiji/p/16900239.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南