httpclient多线程
时间: 2023-07-12 13:00:24 浏览: 116
httpclient著名的多线程框架
3星 · 编辑精心推荐
HTTPClient是一个开源的HTTP通信框架,支持多线程并发请求。要在多线程环境下使用HTTPClient,可以使用多线程池来管理HTTP请求线程。下面是使用HTTPClient进行多线程请求的一个简单示例:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpThreadDemo {
public static void main(String[] args) {
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 创建HttpGet请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
// 提交多个请求
for (int i = 0; i < 10; i++) {
executorService.submit(new HttpTask(httpClient, httpGet));
}
// 关闭线程池
executorService.shutdown();
}
static class HttpTask implements Runnable {
private HttpClient httpClient;
private HttpGet httpGet;
public HttpTask(HttpClient httpClient, HttpGet httpGet) {
this.httpClient = httpClient;
this.httpGet = httpGet;
}
@Override
public void run() {
try {
// 执行请求
httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
在上面的示例中,我们创建了一个线程池,然后提交了10个HTTP请求任务。每个任务都是一个独立的线程,通过HttpClient对象执行一个HttpGet请求。最后,我们关闭了线程池。
阅读全文