HttpClient http POST连接

Post:

public void httpDoPost(String url, JSONObject params) {

    //创建默认Client实例

    CloseableHttpClient client = HttpClients.createDefault();

    //创建post请求实例

    HttpPost httpPost =new HttpPost(url);

    //添加请求头信息

    httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

    try {

        //传递参数   防止乱码

        httpPost.setEntity(new StringEntity(params.toJSONString(), "utf-8"));

        //得到响应内容 包含状态码,头信息等

        CloseableHttpResponse resp = client.execute(httpPost);

        //  获取响应entity,等同于response中body的内容

        HttpEntity respEntity = resp.getEntity();

        try{

            //将响应内容转换成String输出

            String result = EntityUtils.toString(respEntity, "UTF-8");

        }final{

            //关闭响应接收

            resp.close();

        }

        }catch(Exception e){

            new RuntimeException(e);

        }final{

            client.close();

        }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。