httpClient POST传递JSON

Maven

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.5</version>
</dependency>

JAVA代码

public static String doPostJson(String url, String bodyData){
        String result = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            // 请求地址
            HttpPost httpPost = new HttpPost(url); 
            //请求头
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            //请求参数
            httpPost.setEntity(new StringEntity(bodyData, "utf-8"));
            // 得到返回的response
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().toString().contains("200")) {
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + result);
            }
        } catch (Exception e) {
        } finally {
            try {
                // 关闭httpClient
                if (null != httpClient) {
                    httpClient.close();
                }
                // 关闭response
                if (null != response) {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                }
            }catch (IOException e){

            }
        }
        return result;
    }

 


版权声明:本文为qq_35840028原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。