httpsend未能正常发送utf-8字符的问题

之前只设置了httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); 这还不够,还需要额外的请求头的参数设置,代码如下

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
import java.nio.charset.Charset;

public class HttpUtils {
    public static String sendHttpPost(String url, String JSONBody) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(JSONBody.toString(), Charset.forName("UTF-8")));
        CloseableHttpResponse response = httpClient.execute(httpPost);
//      System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
//      System.out.println(responseContent);
        response.close();
        httpClient.close();
        return responseContent;
    }
}

相关依赖


            org.apache.httpcomponents
            httpcore
            4.4.5
        
        
            org.apache.httpcomponents
            httpclient
            4.5.6
        
        
            org.apache.httpcomponents
            httpmime
            4.5.2
        

参考资料来源:
https://blog.csdn.net/shuchongqu/article/details/88948589
https://www.cnblogs.com/soundcode/p/6560947.html

你可能感兴趣的:(httpsend未能正常发送utf-8字符的问题)