帮我写一份关于httpclient的讲课课件
时间: 2024-06-09 09:11:48 浏览: 92
httpclient-tutorial
好的,下面是一份httpclient讲课课件:
# HttpClient讲课课件
## 什么是HttpClient?
HttpClient是Apache基金会的一个开源项目,它是一个用于处理HTTP请求和响应的Java库。HttpClient可以被用于客户端的HTTP通信。
## HttpClient的特点
- 支持HTTP、HTTPS、FTP等协议
- 支持连接池管理
- 支持自定义连接重试策略
- 支持自定义身份验证
- 支持代理服务器
- 支持Cookie管理
- 支持请求缓存
- 支持请求队列管理
- 支持HTTP/2协议
## HttpClient的版本
HttpClient有两个版本:HttpClient 3.x和HttpClient 4.x。
HttpClient 3.x是较早的版本,不再维护和更新。
HttpClient 4.x是目前使用最广泛的版本,它是基于Java5的并发框架构建的,支持HTTP协议的所有请求方法,包括GET、POST、PUT、DELETE等。使用HttpClient 4.x可以更加方便地进行HTTP通信。
## HttpClient的使用
### Maven依赖
```
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
```
### 创建HttpClient对象
```java
CloseableHttpClient httpclient = HttpClients.createDefault();
```
### 创建HttpGet对象
```java
HttpGet httpGet = new HttpGet("http://www.baidu.com");
```
### 发送HttpGet请求
```java
CloseableHttpResponse response = httpclient.execute(httpGet);
```
### 解析响应
```java
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
```
### 关闭连接
```java
response.close();
httpclient.close();
```
## HttpClient的进阶使用
### 自定义请求头
```java
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
```
### 发送HttpPost请求
```java
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpclient.execute(httpPost);
```
### 使用连接池
```java
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
```
### 自定义连接重试策略
```java
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// Retry if the request is considered idempotent
return !(request instanceof HttpEntityEnclosingRequest);
}
};
CloseableHttpClient httpclient = HttpClients.custom()
.setRetryHandler(myRetryHandler)
.build();
```
### 使用代理服务器
```java
HttpHost proxy = new HttpHost("localhost", 8888, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
CloseableHttpResponse response = httpclient.execute(httpPost);
```
### Cookie管理
```java
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
```
### 请求缓存
```java
HttpCacheStorage cacheStorage = new BasicHttpCacheStorage();
CacheConfig cacheConfig = CacheConfig.custom()
.setMaxCacheEntries(1000)
.setMaxObjectSize(8192)
.build();
HttpClientContext context = HttpClientContext.create();
context.setCacheConfig(cacheConfig);
context.setHttpCacheStorage(cacheStorage);
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = httpclient.execute(httpGet, context);
```
### 请求队列管理
```java
ExecutorService executorService = Executors.newFixedThreadPool(10);
HttpProcessor processor = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("MyAgent-HTTP/1.1"))
.add(new RequestExpectContinue(true))
.build();
HttpAsyncRequestExecutor requestExec = new HttpAsyncRequestExecutor();
HttpAsyncRequestProducer producer1 = HttpAsyncMethods.create(
new HttpGet("http://localhost/"));
HttpAsyncRequestProducer producer2 = HttpAsyncMethods.create(
new HttpGet("http://localhost/"));
Future<HttpResponse> future1 = requestExec.execute(
new BasicAsyncRequestProducer(
HttpHost.create("localhost"),
producer1),
new BasicAsyncResponseConsumer(),
executorService,
context,
new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
System.out.println("Response: " + result.getStatusLine());
}
@Override
public void failed(Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
@Override
public void cancelled() {
System.out.println("Cancelled");
}
});
Future<HttpResponse> future2 = requestExec.execute(
new BasicAsyncRequestProducer(
HttpHost.create("localhost"),
producer2),
new BasicAsyncResponseConsumer(),
executorService,
context,
new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
System.out.println("Response: " + result.getStatusLine());
}
@Override
public void failed(Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
@Override
public void cancelled() {
System.out.println("Cancelled");
}
});
```
阅读全文