美文网首页Java
HttpClient请求Demo

HttpClient请求Demo

作者: 柴建龙 | 来源:发表于2018-10-08 17:15 被阅读0次
    public static String postDemo(String url,Map<String,String> 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<NameValuePair> list=new ArrayList<>();
        if(map!=null){
            for(Map.Entry<String,String> 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

        本文链接:https://www.haomeiwen.com/subject/rsujaftx.html