您的位置:首页 > 编程语言 > Java开发

java post请求设置body中文乱码问题

2017-01-16 16:11 375 查看
public static String postBody(String url, String body) {

        // 实例化httpClient

        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 实例化post方法

        HttpPost httpPost = new HttpPost(url);

        // 结果

        CloseableHttpResponse response = null;

        String content = null;

        httpPost.setHeader("Content-Type" , "application/json");

        try {

            // 将参数给post方法

            if (body != null) {

                StringEntity stringEntity = new StringEntity(body , "UTF-8");

                httpPost.setEntity(stringEntity);

            }

            // 执行post方法

            response = httpclient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == 200) {

                try {

                    content = EntityUtils.toString(response.getEntity(), "UTF-8");

                } finally {

                    response.close();

                }

            }

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                httpclient.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return content;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐