In the example below I create one Java 11 httpClient and then create multiple concurrent HttpRequests.
- Is this bad practice?
- Should each HttpRequest have its own HttpClient?
- Is there an upper limit on the number of HttpRequests a HttpClient can have?
Code
private static void httpClientExample(){
HttpClient httpClient = HttpClient.newHttpClient();
System.out.println("TP1");
var task1 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://www.bing.com/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
var task2 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://openjdk.java.net/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
var task3 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://www.google.co.uk/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
System.out.println("Requests Sent");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread Completed");
}