java 使用线程池的http连接代码
时间: 2024-05-15 15:19:22 浏览: 71
以下是一个Java使用线程池的HTTP连接代码示例:
```
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpThreadPoolExample {
public static void main(String[] args) {
// 创建一个线程池,用于同时处理多个HTTP请求
ExecutorService executor = Executors.newFixedThreadPool(5);
// 创建一个HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建多个HTTP请求任务,每个任务发送一个HTTP GET请求
for (int i = 0; i < 10; i++) {
HttpGet httpGet = new HttpGet("https://jsonplaceholder.typicode.com/posts/" + i);
executor.execute(new HttpTask(httpClient, httpGet));
}
// 关闭线程池和HTTP客户端
executor.shutdown();
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class HttpTask implements Runnable {
private CloseableHttpClient httpClient;
private HttpGet httpGet;
public HttpTask(CloseableHttpClient httpClient, HttpGet httpGet) {
this.httpClient = httpClient;
this.httpGet = httpGet;
}
@Override
public void run() {
try {
// 发送HTTP请求并获取响应
HttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码中,我们创建了一个线程池,用于同时处理多个HTTP请求。每个HTTP请求都被封装成一个任务,并由线程池中的线程处理。每个任务都创建了一个HTTP客户端,并发送一个HTTP GET请求。在发送请求后,我们打印出响应状态行的内容。最后,我们关闭线程池和HTTP客户端。
阅读全文