java一次请求多个http
时间: 2023-06-14 08:05:06 浏览: 71
在Java中,可以使用多线程或异步请求来同时发送多个HTTP请求。以下是使用多线程的示例代码:
```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultiThreadedHttpRequest {
public static void main(String[] args) throws IOException {
String[] urls = {"http://www.example.com/page1", "http://www.example.com/page2", "http://www.example.com/page3"};
for (String url : urls) {
Thread thread = new Thread(() -> {
try {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response code for " + url + " is " + responseCode);
} catch (IOException e) {
e.printStackTrace();
}
});
thread.start();
}
}
}
```
这个示例代码创建了一个包含多个URL的字符串数组,并使用多线程循环遍历每个URL。每个线程都会创建一个HTTP连接,并发送一个GET请求。当服务器响应时,将打印响应代码。注意,这种方法可能会对服务器造成较大的负载,因此请确保不要过度使用。
还有一种使用异步请求的方法是使用Java 11中引入的CompletableFuture类。以下是一个示例代码:
```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class AsyncHttpRequest {
public static void main(String[] args) {
List<URI> uris = Arrays.asList(
URI.create("http://www.example.com/page1"),
URI.create("http://www.example.com/page2"),
URI.create("http://www.example.com/page3")
);
HttpClient client = HttpClient.newBuilder().build();
for (URI uri : uris) {
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(
HttpRequest.newBuilder(uri).GET().build(), HttpResponse.BodyHandlers.ofString());
futureResponse.thenAccept(response -> {
System.out.println("Response code for " + uri + " is " + response.statusCode());
});
}
}
}
```
这个示例代码创建了一个包含多个URI的URI列表,并使用循环遍历每个URI。使用Java 11中的HttpClient类创建了一个异步请求,并使用CompletableFuture类等待响应。当服务器响应时,将打印响应代码。这种方法可能对服务器的负载较小,因为它使用异步请求来发送HTTP请求。