温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何正确的使用HttpClient方法

发布时间:2021-01-11 16:26:07 来源:亿速云 阅读:522 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关如何正确的使用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;
  }

以上就是如何正确的使用HttpClient方法,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI