HttpClient的使用详解与实战

一、HttpClient简介


二、使用HttpClient获取网页内容

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
@Test
public void test {
        // 打开浏览器
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 输入url地址
        HttpGet httpGet = new HttpGet("https://www.baidu.com/");
        CloseableHttpResponse response = null;
        try {
            // 敲回车,发送请求,获取响应
            response = httpClient.execute(httpGet);
            // 获取内容
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (response != null){
                    response.close();
                }
                if (httpGet != null){
                    httpGet.releaseConnection();
                }
                if (httpClient!= null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

可以看到请求的结果为百度源代码,可以放到EditPlus中进行预览

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

三、发送get请求

客户端

@Test
void sendGet(){
    CloseableHttpClient client = null;
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    try {
        client = HttpClientBuilder.create().build();
        // 构建参数列表【BasicNameValuePair】
        List<BasicNameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("page","1"));
        pairs.add(new BasicNameValuePair("limit","5"));
        // 设置参数的编码
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs,"utf-8");
        // 将参数转成page=1&limit=5格式
        String params = EntityUtils.toString(urlEncodedFormEntity, "utf-8");
        System.out.println(params);
        httpGet = new HttpGet("http://localhost:8080/user/queryUserList?"+params);
        // 发送请求
        response = client.execute(httpGet);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (response != null) {
                response.close();
            }

            if (httpGet != null){
                httpGet.releaseConnection();
            }

            if (client != null){
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端

@GetMapping("queryUserList")
public PageBean queryUserList(UserVO vo){
    return userService.queryUserList(vo);
}

四、发送Post请求

客户端

@Test
void sendPost(){
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        httpPost = new HttpPost("http://localhost:8080/user/addUser");
        // 构建参数列表【BasicNameValuePair】
        List<BasicNameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("name","张三"));
        pairs.add(new BasicNameValuePair("sex","1"));
        // 设置参数编码
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs,"utf-8");
        // 发送请求之前给httpPost设置参数
        httpPost.setEntity(urlEncodedFormEntity);
        response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (response != null) {
                response.close();
            }

            if (httpPost != null){
                httpPost.releaseConnection();
            }

            if (httpClient != null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端

@PostMapping("addUser")
public ResultObj addUser(User user){
    try {
        String salt = IdUtil.simpleUUID().toUpperCase();
        user.setSalt(salt);
        user.setPwd(new Md5Hash(Constant.USER_PASSWORD,salt,2).toString());
        userService.addUser(user);
        return ResultObj.ADD_SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
        return ResultObj.ADD_ERROR;
    }
}

五、封装get请求

public static String sendGet(String url, Map<String,String> params){
    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    String result = "";
    try {
        httpClient = HttpClientBuilder.create().build();
        httpGet = new HttpGet(url);
        // 设置参数
        if (null != params && params.size() > 0){
            List<BasicNameValuePair> pairList = new ArrayList<>();
            params.forEach((x,y) -> pairList.add(new BasicNameValuePair(x,y)));
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList,"utf-8");
            // 将参数转成page=1&limit=5格式
            String param = EntityUtils.toString(urlEncodedFormEntity, "utf-8");
            httpGet = new HttpGet(url+"?"+param);
        }
        response = httpClient.execute(httpGet);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        close(response,httpGet,httpClient);
    }
    return result;
}

客户端

@Test
void sendGetUtil(){
    Map<String,String> map = new HashMap<>();
    map.put("page","1");
    map.put("limit","5");
    String result = HttpClientUtil.sendGet("http://localhost:8080/user/queryUserList", map);
    System.out.println(result);
}

六、封装传递键值对格式的post请求

public static String sendPost(String url, Map<String,String> params){
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    String result = "";
    try {
        httpClient = HttpClientBuilder.create().build();
        httpPost = new HttpPost(url);
        // 设置参数
        if (null != params && params.size() > 0){
            List<BasicNameValuePair> pairList = new ArrayList<>();
            params.forEach((x,y) -> pairList.add(new BasicNameValuePair(x,y)));
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList,"utf-8");
            httpPost.setEntity(urlEncodedFormEntity);
        }
        response = httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        close(response,httpPost,httpClient);
    }
    return result;
}

客户端

@Test
void sendPostUtil(){
    Map<String,String> map = new HashMap<>();
    map.put("name","张三");
    map.put("sex","1");
    String result = HttpClientUtil.sendPost("http://localhost:8080/user/addUser", map);
    System.out.println(result);
}

七、封装传递Json格式的post请求

public static String sendPostJson(String url, Map<String,String> params){
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = HttpClientBuilder.create().build();
            httpPost = new HttpPost(url);
            // 设置参数
            if (null != params && params.size() > 0){
                String paramJson = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(paramJson,"utf-8");
                stringEntity.setContentType("application/json;charset=utf-8");
                httpPost.setEntity(stringEntity);
            }
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(response,httpPost,httpClient);
        }
        return result;
    }

服务端

@PostMapping("addUser")
    public ResultObj addUser(@RequestBody User user){
        try {
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);
            user.setPwd(new Md5Hash(Constant.USER_PASSWORD,salt,2).toString());
            userService.addUser(user);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

对于关流的封装

public static void close(CloseableHttpResponse response,HttpRequestBase httpRequestBase,CloseableHttpClient httpClient){
    try {
        if (response != null) {
            response.close();
        }

        if (httpRequestBase!= null){
            httpRequestBase.releaseConnection();
        }
        
        if (httpClient != null){
            httpClient.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 23
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值