HttpClient无乱码
Posted julian-chang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient无乱码相关的知识,希望对你有一定的参考价值。
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public static String doPost(String url, String json) { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); String result = ""; try { StringEntity s = new StringEntity(json,"utf-8"); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//设置contentType post.addHeader("Content-Type", "application/json;charset=UTF-8"); post.setEntity(s); HttpResponse res = httpclient.execute(post); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = res.getEntity(); result = EntityUtils.toString(res.getEntity()); } } catch (Exception e) { throw new RuntimeException(e); } return result; }
以上是关于HttpClient无乱码的主要内容,如果未能解决你的问题,请参考以下文章
HttpClient发送请求后得到的响应内容出现部分乱码的问题