public static String doPostByJson(String url, JSONObject json){
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String response = null;
try {
StringEntity s = new StringEntity(json.toString(),"utf-8"); //这里是关键,后面要跟上字符集格式
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = result;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
之前直接用然后接受乱码,发现在设置字符串对象的时候需要写汉字编码字符集格式.
httpclient用post方式发送json乱码错误解决
最新推荐文章于 2024-08-06 17:13:24 发布