HTTPClient简单使用

概述

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。

虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

参考博文

环境

最常用的http请求库是httpcomponents,为了方便处理json数据,导入阿里的fastjson。

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5</version>
</dependency>

<!--如果需要灵活的传输文件,引入此依赖后会更加方便-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.5</version>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.73</version>
</dependency>

入门

使用步骤:

  • 创建HttpClient对象
  • 创建HttpPost或者HttpGet请求
  • 为HttpPost设置header和config
  • 如果post请求有参数,先设置post请求参数,get请求直接拼到url后面就可以了
  • 使用HttpClient执行(execute)get、post请求
  • 拿到responseEntity,使用EntityUtils工具类解析responseEntity内容

Get请求

public static JSONObject httpGet(String url) {
  //1.创建httpClient对象
  HttpClient httpClient = HttpClientBuilder.create().build();
  try {
    //2.封装、发送get请求
    HttpGet request = new HttpGet(url);
    HttpResponse response = httpClient.execute(request);
    //3.读取服务器返回过来的json字符串数据
    String result = EntityUtils.toString(response.getEntity());
  return jsonResult;
}

Post请求

/**
* post请求,第二个参数表示post请求参数
*/
public static JSONObject httpPost(String url, String jsonStr) {
  //1. 创建httpClient对象
  HttpClient httpClient = HttpClientBuilder.create().build();
  JSONObject jsonResult = new JSONObject();
  //2. 封装post请求
  HttpPost method = new HttpPost(url);
  //3. 进行配置
  method.setConfig(getRequestConfig());
  //4. 设置header
  //5. 设置post请求参数
  StringEntity entity = new StringEntity(jsonStr, "utf-8");
  method.addHeader("content-type", "application/json");
  method.setEntity(entity);

  //6. 发送post请求,解析参数
  HttpResponse result = httpClient.execute(method);
  String str = EntityUtils.toString(result.getEntity());
}

// 设置超时时间
public static RequestConfig getRequestConfig() {
  return RequestConfig.custom()
    .setConnectTimeout(10000)
    .setSocketTimeout(35000)
    .setConnectionRequestTimeout(6000)
    .build();
}

HttpClient连接池

在处理高并发情况的时候最好设置一下HTTP连接池,因为创建HTTP连接是非常耗时的。

//创建HttpClient对象并配置连接池
public static CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

  SSLContextBuilder builder = new SSLContextBuilder();
  builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

  // 配置同时支持 HTTP 和 HTPPS
  Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
    .register("http", PlainConnectionSocketFactory.getSocketFactory())
    .register("https", sslsf)
    .build();
  // 初始化连接管理器
  poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  // 同时最多连接数
  poolConnManager.setMaxTotal(640);
  // 设置最大路由
  poolConnManager.setDefaultMaxPerRoute(320);
  return HttpClients.custom()
    .setConnectionManager(poolConnManager)
    .build();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收 HTTP 响应。它提供了简化的 API,使得进行 HTTP 通信变得更加容易。 要使用 HttpClient,首先需要在项目中引入 HttpClient 的依赖。具体的操作方式取决于你使用的开发环境和构建工具。一般来说,如果是使用 Maven 进行项目管理,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 如果是使用 Gradle 进行项目管理,可以在 build.gradle 文件中添加以下依赖: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` 接下来就可以在代码中使用 HttpClient 来发送 HTTP 请求了。下面是一个简单的示例: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://example.com"); HttpResponse response = httpClient.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); } } ``` 上述示例中,我们创建了一个 HttpClient 实例,并使用该实例发送了一个 GET 请求到 "http://example.com"。获取到的响应存储在 HttpResponse 对象中,我们可以通过调用 `getStatusCode()` 方法获取响应的状态码。 当然,HttpClient 还提供了丰富的 API,可以进行更加复杂的 HTTP 请求和处理。你可以参考 HttpClient 的官方文档来了解更多详细的使用方法和示例。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值