您可以使用 Java 中的 HttpClient 来模拟 POST 请求,并通过多线程来实现并发请求。下面是一个简单的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentPostRequests {
public static void main(String[] args) {
String url = "your_post_url"; // 替换为实际的POST接口URL
String requestBody = "your_request_body"; // 替换为实际的请求体
ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个包含10个线程的线程池
for (int i = 0; i < 71; i++) {
executorService.submit(() -> {
try {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
StringEntity stringEntity = new StringEntity(requestBody);
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
System.out.println("Response: " + responseBody.toString());
// 如果是最后一次请求,关闭线程池
if (Thread.activeCount() == 2) {
executorService.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
在这个示例中,我们创建了一个包含 10 个线程的线程池,然后提交了 71 个任务。每个任务都是一个 POST 请求,并发发送到目标 URL。最后一次请求的响应将被打印出来。