请用Java 生成HttpClient 高并发请求第三方接口
时间: 2024-04-14 16:30:24 浏览: 79
当使用 Java 生成 HttpClient 高并发请求第三方接口时,你可以使用 Apache HttpClient 库。以下是一个简单的示例代码:
```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;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentHttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
ExecutorService executorService = Executors.newFixedThreadPool(10); // 并发线程池
// 发起并发请求
for (int i = 0; i < 100; i++) {
executorService.execute(() -> {
HttpGet httpGet = new HttpGet("https://api.example.com/endpoint"); // 替换为实际的接口地址
try {
HttpResponse response = httpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder responseContent = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
System.out.println("Response: " + responseContent.toString());
} catch (IOException e) {
e.printStackTrace();
}
});
}
executorService.shutdown(); // 关闭线程池
}
}
```
在上述示例中,我们首先创建了一个 HttpClient 实例,并创建了一个具有固定线程数的线程池。然后使用线程池发起并发请求,每个线程执行一个 HttpGet 请求,并处理响应结果。
请注意,在实际使用中,你可能需要根据第三方接口的要求进行设置,如请求头、请求参数等。此外,还需要适当处理异常、重试机制和流量控制等情况,以保证请求的稳定性和性能。
阅读全文