HttpClient请求Demo

public static String postDemo(String url,Map map,String encoding){
    String body="";
    //1、创建HttpClient对象
    CloseableHttpClient httpClient= HttpClients.createDefault();
    HttpClientUtil httpClientUtil=new HttpClientUtil();
    //2、创建请求方法对象
    HttpPost post= (HttpPost) httpClientUtil.getRequest(url,HttpMethods.POST);
    List list=new ArrayList<>();
    if(map!=null){
        for(Map.Entry entry:map.entrySet()){
            list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
    }
    try {
        //3、设置参数到请求方法对象中
        post.setEntity(new UrlEncodedFormEntity(list,encoding));
        Log.info("请求url:"+url);
        Log.info("请求参数:"+list.toString());
        try {
               //4、执行请求
            CloseableHttpResponse response=httpClient.execute(post);
            //5、获取结果实体
            HttpEntity entity=response.getEntity();
            if(entity!=null){
                //6、将结果实体转换为字符串
                body= EntityUtils.toString(entity,encoding);
            }
            EntityUtils.consume(entity);
            //7、释放连接
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return body;
}

你可能感兴趣的:(HttpClient请求Demo)