【Java】HttpClient 5 CloseableHttpClient使用

依赖

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>

引入包

import com.alibaba.fastjson2.JSON;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

POST 有参数

public A findXxx(String code) {
    // 定义一个A对象,用于返回
    A a= null;
    // 创建HttpClient
    CloseableHttpClient client = HttpClients.createDefault();
    // 创建HttpPost
    HttpPost httpPost = new HttpPost(url);
    log.info("HttpUrl:{}", url);
    // 设置Headers
    httpPost.setHeader("xxx", "xxx");
    // 设置参数
    Map<String, Object> params = new HashMap<>();
    params.put("xxx", "xxx");
    httpPost.setEntity(new StringEntity(JSON.toJSONString(params)));
    // 执行
    try (CloseableHttpResponse response = client.execute(httpPost)) {
        if (response.getCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            // 获取json字符串
            String jsonString = EntityUtils.toString(httpEntity);
            log.info("findXxxResponse:{}", jsonString);
            if (jsonString.contains("errorCode")) {
                log.error("findXxxFail:{}", jsonString);
            } else {
                // 获取json对象
                a = JSON.parseObject(jsonString, A.class);
            }
        } else {
            log.error("findXxxFail:{}", response);
        }
    } catch (Exception e) {
        log.error(ResultCode.HTTP_FAIL.message(), e);
    } finally {
        // 释放连接资源
        httpPost.reset();
    }
    return a;
}

GET 无参数

public A findXxx(String code) {
    // 定义一个A对象,用于返回
    A a= null;
    // 创建HttpClient
    CloseableHttpClient client = HttpClients.createDefault();
    // 拼接url
    String url = xxxUrl + "?xxx=xxx";
    // 创建HttpGet
    HttpGet httpGet = new HttpGet(url);
    log.info("HttpUrl:{}", url);
    // 设置Headers
    httpGet.setHeader("xxx", "xxx");
    // 执行
    try (CloseableHttpResponse response = client.execute(httpGet)) {
        if (response.getCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            // 获取json字符串
            String jsonString = EntityUtils.toString(httpEntity);
            log.info("findXxxResponse:{}", jsonString);
            if (jsonString.contains("errorCode")) {
                log.error("findXxxFail:{}", jsonString);
            } else {
                // 获取json对象
                a = JSON.parseObject(jsonString, A.class);
            }
        } else {
            log.error("findXxxFail:{}", response);
        }
    } catch (Exception e) {
        log.error(ResultCode.HTTP_FAIL.message(), e);
    } finally {
        // 释放连接资源
        httpGet.reset();
    }
    return a;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会为您介绍Java使用CloseableHttpClient发送HTTP请求的方法。 CloseableHttpClient是Apache HttpClient库中的一个类,它提供了一种发送HTTP请求的简单方法。下面是一些基本的使用方法: 1. 创建CloseableHttpClient对象 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpRequest对象 HttpRequest是一个接口,它定义了HTTP请求的各种方法和属性。在使用CloseableHttpClient发送HTTP请求之前,我们需要先创建一个HttpRequest对象。常用的HttpRequest实现类有HttpGet、HttpPost、HttpPut、HttpDelete等,具体选择哪种实现类取决于你要发送的HTTP请求的类型。 例如,我们可以创建一个HttpGet对象: ```java HttpGet httpGet = new HttpGet("http://www.example.com"); ``` 3. 执行HTTP请求 创建好HttpRequest对象之后,我们就可以使用CloseableHttpClient对象来执行HTTP请求了。执行HTTP请求的方式很简单,只需要调用CloseableHttpClient对象的execute方法,并传入HttpRequest对象即可。 例如,我们可以执行上面创建的HttpGet对象: ```java CloseableHttpResponse response = httpClient.execute(httpGet); ``` 4. 处理HTTP响应 执行HTTP请求之后,我们需要处理HTTP响应。CloseableHttpResponse是一个接口,它定义了HTTP响应的各种方法和属性。我们可以使用这些方法来获取HTTP响应的状态码、响应头、响应体等信息。 例如,我们可以获取HTTP响应的状态码: ```java int statusCode = response.getStatusLine().getStatusCode(); ``` 5. 关闭CloseableHttpClient对象 最后,我们需要关闭CloseableHttpClient对象。关闭CloseableHttpClient对象可以释放与之相关的资源,例如HTTP连接、线程等。我们可以使用CloseableHttpClient对象的close方法来关闭它。 例如: ```java httpClient.close(); ``` 以上就是使用CloseableHttpClient发送HTTP请求的基本方法。希望能对您有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值