HttpClient用法

1.简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。

2.特性

  1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

  2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

  3. 支持HTTPS协议。

  4. 通过Http代理建立透明的连接。

  5. 利用CONNECT方法通过Http代理建立隧道的https连接。

  6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

  7. 插件式的自定义认证方案。

  8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

  9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

  10. 自动处理Set-Cookie中的Cookie。

  11. 插件式的自定义Cookie策略。

  12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

  13. Response的输入流可以有效的从socket服务器直接读取相应内容。

  14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

  15. 直接获取服务器发送的response code和 headers。

  16. 设置连接超时的能力。

  17. 实验性的支持http1.1 response caching。

  18. 源代码基于Apache License 可免费获取。

3.使用方法

  1. 创建HttpClient对象。

  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

  6. 释放连接。无论执行方法是否成功,都必须释放连接

4、实例

4.1 导入pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wo</groupId>
    <artifactId>HttpClient_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>
</project>

4.2.get请求方式

@RequestMapping("findAll")
    public String findAll() throws Exception{
        //获得Http客户端
        CloseableHttpClient build = HttpClientBuilder.create().build();
        //创建get请求
        HttpGet httpGet = new HttpGet("http://localhost:8088/lunbo/findAll");
        //执行请求
        CloseableHttpResponse execute = build.execute(httpGet);
        //解析返回值
        StatusLine statusLine = execute.getStatusLine();
        //获取到返回状态码
        System.out.println("状态码为:"+statusLine.getStatusCode());
        String s = EntityUtils.toString(execute.getEntity());
        build.close();
        execute.close();
        return s;
    }

4.3 post请求方式

//post路径传参
    @RequestMapping("/findAllPost/{page}/{size}")
    public String findAll(@PathVariable("page") int page,@PathVariable("size") int size) throws Exception {
        //获得Http客户端
        CloseableHttpClient build = HttpClientBuilder.create().build();
        //创建post请求
        HttpPost httpPost = new HttpPost("http://localhost:8088/position/findAll/"+page+"/"+size);
        //执行请求
        CloseableHttpResponse execute = build.execute(httpPost);
        //解析返回值
        StatusLine statusLine = execute.getStatusLine();
        //获取到返回状态码
        System.out.println("状态码为:"+statusLine.getStatusCode());
        String s = EntityUtils.toString(execute.getEntity());
        build.close();
        execute.close();
        return s;
    }

    //post map传参
    @RequestMapping("findById")
    public String findById(@RequestParam("id") Integer id)throws Exception{
        //创建httpclicent请求对象
        CloseableHttpClient build = HttpClientBuilder.create().build();
        //声明请求方式
        HttpPost httpPost = new HttpPost("http://localhost:8088/position/findById");
        //声明携带参数
        Map map=new HashMap<>();
        map.put("id",id);
        //将map转换为json格式
        Object o = JSONObject.toJSON(map);
        //设置请求 参数的编码格式
        StringEntity stringEntity = new StringEntity(o.toString(), "utf-8");
        //将参数设置到请求对象中
        httpPost.setEntity(stringEntity);
        //设置content-Type
        httpPost.setHeader("Content-Type","application/json");
        //执行请求
        CloseableHttpResponse execute = build.execute(httpPost);
        //解析返回值
        StatusLine statusLine = execute.getStatusLine();
        //获取到返回状态码
        System.out.println("状态码为:"+statusLine.getStatusCode());
        String s = EntityUtils.toString(execute.getEntity());
        build.close();
        execute.close();
        return s;
    }
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值