原文网址:HTTP客户端--介绍_IT利刃出鞘的博客-CSDN博客
HTTP客户端
简介
HTTP是很常用的互联网网络协议,在使用时,不可能直接调用协议,因此需要对HTTP协议进行封装,将网络传输的功能转化为方法,开发人员就可以直接调用。
HTTP客户端主要有:HttpUrlConnect、HttpClient、OkHttp
项 | HttpUrlConnect | HttpClient | OkHttp |
来源 | JDK自带 | Apache | Square |
简介 | 易用与灵活性差 | 可修改超时时间。 易用性低于OkHttp | 不能修改超时时间。(例如创建单例连接后无法配置超时时间) |
性能 | 差 | 居中 | 最好 |
OkHttp
其他网址
HTTP客户端--OkHttp_feiying0canglang的博客-CSDN博客
HttpClient
官网
官方下载:http://hc.apache.org/downloads.cgi
官网:Apache HttpComponents – HttpClient Overview
特性
- 基于标准、纯净的Java语言,实现了HTTP1.0和HTTP1.1。
- 以可扩展的面向对象的结构实现了HTTP全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
- 支持加密的HTTPS协议(HTTP通过SSL协议)。
- 通过HTTP代理方式建立透明的连接。
- 利用CONNECT方法通过HTTP代理建立隧道的HTTPS连接。
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
- 插件式的自定义认证方案。
- 可插拔的安全套接字工厂,使得接入第三方解决方案变得更容易
- 连接管理支持使用多线程的的应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
- 自动化处理Set-Cookie:来自服务器的头,并在适当的时候将它们发送回cookie。
- 可以自定义Cookie策略的插件化机制。
- Request的输出流可以避免流中内容体直接从socket缓冲到服务器。
- Response的输入流可以有效的从socket服务器直接读取相应内容。
- 在HTTP1.0和HTTP1.1中使用用KeepAlive来保持持久连接。
- 可以直接获取服务器发送的响应码和响应头部。
- 具备设置连接超时的能力。
- 支持HTTP/1.1 响应缓存。
- 源代码基于Apache License 可免费获取。
使用步骤
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
官方文档的示例
//1.获得一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一个get请求
HttpGet httpget = new HttpGet("http://localhost/");
//3.执行get请求并返回结果
CloseableHttpResponse response = httpclient.execute(httpget);
try {
//4.处理结果
} finally {
response.close();
}
修改SpringBoot默认HTTP客户端
其他网址
Spring Boot 工程化最佳实践 - 知乎
Changing HttpClient in Spring RestTemplate - Bytesville
简介
Spring Boot 项目中,底层涉及网络请求的组件有 RestTemplate、Feign 和 Zuul,它们分别有自己默认的 HTTP 请求客户端,很多时候为了获得更好的性能,我们需要替换底层默认的 HTTP 客户端。
说明
OkHttp相对HttpClient优势明显,且配置简单,本处只配置okhttp作为示例。
RestTemplate
RestTemplate 默认使用的是 JDK 原生的 HttpURLConnection。
可以实现 Spring Cloud Commons 提供的 OkHttpClientFactory 并进行自定义的配置:
package com.example.config;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
public class OkHttpClientFactoryImpl implements OkHttpClientFactory {
@Override
public OkHttpClient.Builder createBuilder(boolean disableSslValidation) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
ConnectionPool okHttpConnectionPool = new ConnectionPool(50, 30, TimeUnit.SECONDS);
builder.connectionPool(okHttpConnectionPool);
builder.connectTimeout(20, TimeUnit.SECONDS);
builder.retryOnConnectionFailure(false);
return builder;
}
}
RestTemplate 中配置使用 Okhttp
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Autowired
@Qualifier("OKSpringCommonsRestTemplate")
ClientHttpRequestFactory okHttpRequestFactory;
@Bean
@Qualifier("OKSpringCommonsRestTemplate")
public RestTemplate createOKCustomRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(okHttpRequestFactory);
return restTemplate;
}
}
Feign
其他网址
Feign系列--配置_feiying0canglang的博客-CSDN博客
说明
Feign 默认使用的是 JDK 原生的 HTTPURLConnection。可以使用 Apache HTTP Client 或者 Okhttp 来进行替换,替换的步骤分为两步,首先引入相关的依赖库,然后修改配置。
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>10.1.0</version>
</dependency>
配置文件
application.yml
feign:
httpclient:
enabled: false
okhttp:
enabled: true
Zuul
其他网址
Zuul 使用的默认 HTTP 客户端是 Apache HTTP Client。替换方法:在配置文件中增加如下配置,并引入对应的依赖函数库即可:
依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.7.2</version>
</dependency>
application.properties
ribbon.httpclient.enabled=false # 不使用httpclient
ribbon.okhttp.enabled=true # 使用 Okhttp