您的位置:首页 > 理论基础 > 计算机网络

HTTPClient POST发送JSON数据 中文无乱码

2017-07-14 11:05 627 查看
**

     * post请求

     * @param url

     * @param json

     * @return

     */

    public static JSONObject doPost(String url,JSONObject json){

        

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost(url);

        JSONObject 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 = JSONObject.fromObject(result);

            }

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        return response;
    }

new StringEntity中添加“UTF-8”编码设置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HTTPCLIEN josn post