HttpClient 使用详解

2 篇文章 0 订阅

HttpClient 介绍

HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于从万维网(WWW:World Wide Web )服务器传输超文本到本地浏览器的传送协议。。

HTTP是一个基于TCP/IP通信协议来传递数据(HTML 文件, 图片文件, 查询结果等)。

HttpClient 就是帮我们实现了所有的Http的方法,比如Get,Post,Put,Delete 等,同时支持Https协议等。


HttpClient 使用前的准备工作

添加pom依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.5</version>
</dependency>

 基本使用方法 

无论多复杂的请求,都可以分为以下几步

  1、创建 HttpClient 

  2、创建请求

  3、执行请求并获取参数

简单理解可以为:1、打开浏览器;2、输入网址;3、回车并查看页面返回的内容;

下面具体介绍用法


Get(无入参,返回一个实体)

postman:

java代码实现:


  @Test
  public void getNoPara() {
    // 0.请求的 uri
    String uri = "http://localhost:8080/sell/buyer/product/one";
    // 1.创建 HttpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 2.创建 Get 请求
    HttpGet httpGet = new HttpGet(uri);

    // 3.初始化响应
    CloseableHttpResponse response = null;

    // 4.执行请求 Get 请求
    try {
      response = httpClient.execute(httpGet);

      // 从响应中获取实体
      HttpEntity responseEntity = response.getEntity();

      // 响应码
      System.out.println("响应状态码" + response.getStatusLine());

      // 响应内容转为string
      String entityString = EntityUtils.toString(responseEntity);
      // json转为对象
      ObjectMapper mapper = new ObjectMapper();
      ProductInfo productInfo = mapper.readValue(entityString, ProductInfo.class);
      System.out.println(productInfo);
    } catch (IOException e) {
      e.printStackTrace();
    }finally {

      // 释放连接
      try {
        if(httpClient!=null){
          httpClient.close();
        }
        if(response!=null){
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

Get(无入参,返回一个封装VO)

postman:

java代码实现:

package com.xmlParsing.entity;

public class ResultVO<T> {

  private Integer code;
  private String msg;
  private T data;


  @Override
  public String toString() {
    return "ResultVO{" +
        "code=" + code +
        ", msg='" + msg + '\'' +
        ", data=" + data +
        '}';
  }

  public Integer getCode() {

    return code;
  }

  public void setCode(Integer code) {
    this.code = code;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  public T getData() {
    return data;
  }

  public void setData(T data) {
    this.data = data;
  }
}
@Test
  public void getNoPara() {
    // 0.请求的 uri
    String uri = "http://localhost:8080/sell/buyer/product/formatOne";
    // 1.创建 HttpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 2.创建 Get 请求
    HttpGet httpGet = new HttpGet(uri);

    // 3.初始化响应
    CloseableHttpResponse response = null;

    // 4.执行请求 Get 请求
    try {
      response = httpClient.execute(httpGet);

      // 从响应中获取实体
      HttpEntity responseEntity = response.getEntity();

      // 响应码
      System.out.println("响应状态码" + response.getStatusLine());

      // 响应内容转为string
      String entityString = EntityUtils.toString(responseEntity);
      // json转为对象
      ObjectMapper mapper = new ObjectMapper();
      ResultVO resultVO = mapper.readValue(entityString, ResultVO.class);
      System.out.println(resultVO.getData());
    } catch (IOException e) {
      e.printStackTrace();
    }finally {

      // 释放连接
      try {
        if(httpClient!=null){
          httpClient.close();
        }
        if(response!=null){
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

Get(无入参,返回一个List)

postman:

java代码实现:


  @Test
  public void getNoPara() {
    // 0.请求的 uri
    String uri = "http://localhost:8080/sell/buyer/product/all";
    // 1.创建 HttpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 2.创建 Get 请求
    HttpGet httpGet = new HttpGet(uri);

    // 3.初始化响应
    CloseableHttpResponse response = null;

    // 4.执行请求 Get 请求
    try {
      response = httpClient.execute(httpGet);

      // 从响应中获取实体
      HttpEntity responseEntity = response.getEntity();

      // 响应码
      System.out.println("响应状态码" + response.getStatusLine());

      // 响应内容转为string
      String entityString = EntityUtils.toString(responseEntity);
      // json转为对象
      ObjectMapper mapper = new ObjectMapper();
      List<ProductInfo> list = mapper
          .readValue(entityString, new TypeReference<List<ProductInfo>>() {});

      list.stream().forEach(p -> System.out.println(p));


    } catch (IOException e) {
      e.printStackTrace();
    }finally {

      // 释放连接
      try {
        if(httpClient!=null){
          httpClient.close();
        }
        if(response!=null){
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

Get(有入参)

postman:

java代码实现:

  @Test
  public void getResult() {

    // 1、 创建 httpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 2、定义uri 并创建 Get 请求
    URI uri = null;
    try {
      uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080)
          .setPath("/sell/buyer/product/getResult").setParameter("value", "假装我是入参").build();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    HttpGet get = new HttpGet(uri);

    // 3、 初始化响应
    CloseableHttpResponse response = null;


    // 4、 执行 Get 请求
    try {
      response = httpClient.execute(get);

      HttpEntity responseEntity = response.getEntity();
      
      // 响应码
      System.out.println("响应状态码" + response.getStatusLine());

      // 响应内容转为string
      String entityString = EntityUtils.toString(responseEntity);
      System.out.println(entityString);
    } catch (IOException e) {
      e.printStackTrace();
    }finally {

      // 释放连接
      try {
        if(httpClient!=null){
          httpClient.close();
        }
        if(response!=null){
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

Post(无入参)

postman:

java代码实现:

  public void postSimple() {
    // 1、创建 HttpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 2、创建 post 请求
    URI uri = null;
    try {
      uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080)
          .setPath("/sell/buyer/product/product").build();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    HttpPost post = new HttpPost(uri);

    // 3、初始化 response
    CloseableHttpResponse response = null;

    // 4、执行请求
    try {
      response = httpClient.execute(post);
      HttpEntity entity = response.getEntity();

      // 响应内容转为string
      String entityString = EntityUtils.toString(entity);
      // json转为对象
      Gson gson = new Gson().newBuilder().serializeNulls().create();
      ResultVO resultVO = gson.fromJson(entityString, ResultVO.class);
      List<ProductInfo> list = (List<ProductInfo>) resultVO.getData();
      System.out.println(list);

//      list.stream().forEach(productInfo -> System.out.println(productInfo.toString()));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // 释放资源
        if (httpClient != null) {
          httpClient.close();
        }
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

Post有参

 postman:

java代码实现:

  public void saveProduct() {
    // 1、构建入参对象
    ProductInfo productInfo = new ProductInfo();
    productInfo.setProductId("99999");
    productInfo.setProductName("大白菜");
    productInfo.setProductPrice(new BigDecimal("12.34"));
    productInfo.setProductStock(999);
    productInfo.setProductDescription("假装很有范的大白菜~~~~");
    productInfo.setProductIcon("noIcon");
    productInfo.setProductStatus(1);
    productInfo.setCategoryType(1);
    productInfo.setCreateTime(null);
    productInfo.setUpdateTime(null);

    // 2、构建 stringEntity
    Gson gson = new Gson().newBuilder().serializeNulls().create();
    String s = gson.toJson(productInfo);
    StringEntity entity = new StringEntity(s, "UTF-8");

    // 3、创建httpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 4、创建 post 请求
    HttpPost post = new HttpPost("http://localhost:8080/sell/buyer/product/saveProduct");
    post.setEntity(entity);
    post.setHeader("Content-Type", "application/json;charset=utf8");

    // 5、创建相应
    CloseableHttpResponse response = null;
    try {
      response = httpClient.execute(post);
      HttpEntity responseEntity = response.getEntity();
      // 响应内容转为string
      String entityString = EntityUtils.toString(responseEntity);
      System.out.println(entityString);

    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        // 释放资源
        if (httpClient != null) {
          httpClient.close();
        }
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }


  }

Post(复杂入参)

 postman :

java代码实现:

  public void saveProduct() {
    // 1、构建入参对象
    ProductInfo productInfo = new ProductInfo();
    productInfo.setProductId("123999");
    productInfo.setProductName("大白菜");
    productInfo.setProductPrice(new BigDecimal("12.34"));
    productInfo.setProductStock(999);
    productInfo.setProductDescription("假装很有范的大白菜~~~~");
    productInfo.setProductIcon("noIcon");
    productInfo.setProductStatus(1);
    productInfo.setCategoryType(1);
    productInfo.setCreateTime(null);
    productInfo.setUpdateTime(null);

    // 2、构建 stringEntity
    Gson gson = new Gson().newBuilder().serializeNulls().create();
    String s = gson.toJson(productInfo);
    StringEntity entity = new StringEntity(s, "UTF-8");

    // 3、创建httpClient
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // 4、创建 复杂 带参 uri
    List<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("date",LocalDate.now().toString()));
    parameters.add(new BasicNameValuePair("time", LocalTime.now().toString()));
    URI uri = null;
    try {
      uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080)
          .setPath("/sell/buyer/product/saveProduct").setParameters(parameters).build();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    // 5、创建 复杂 post 请求
    HttpPost post = new HttpPost(uri);
    post.setEntity(entity);
    post.setHeader("Content-Type", "application/json;charset=utf8");

    // 6、创建 响应
    CloseableHttpResponse response = null;
    try {

      response = httpClient.execute(post);
      HttpEntity responseEntity = response.getEntity();
      String entityStr = EntityUtils.toString(responseEntity);
      System.out.println(entityStr);

    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        // 释放资源
        if (httpClient != null) {
          httpClient.close();
        }
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

 

参考文献:https://blog.csdn.net/justry_deng/article/details/81042379

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值