首页 > 杂文归档 正文
详解HttpClient用法

 2021-01-11 16:40:04     

上篇文章给大家介绍了HttpClient详细使用示例详解,喜欢的朋友可以点击查看,今天继续给大家介绍HttpClient用法,具体内容如下所示;
1.简介

HttpClient是Apache Jakarta Common下

上篇文章给大家介绍了HttpClient详细使用示例详解,喜欢的朋友可以点击查看,今天继续给大家介绍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:https://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http:https://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http:https://maven.apache.org/POM/4.0.0 http:https://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{
    https://获得Http客户端
    CloseableHttpClient build = HttpClientBuilder.create().build();
    https://创建get请求
    HttpGet httpGet = new HttpGet("http:https://localhost:8088/lunbo/findAll");
    https://执行请求
    CloseableHttpResponse execute = build.execute(httpGet);
    https://解析返回值
    StatusLine statusLine = execute.getStatusLine();
    https://获取到返回状态码
    System.out.println("状态码为:"+statusLine.getStatusCode());
    String s = EntityUtils.toString(execute.getEntity());
    build.close();
    execute.close();
    return s;
  }

4.3 post请求方式

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

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

原文链接:http://www.yuepc.com/a/1640.html

http://www.yuepc.com 为 “沈一博客” 唯一官方服务平台,请勿相信其他任何渠道。