Java - Making multiple requests using HTTP2
Asked Answered
I

1

6

I have not been able to find any great examples to outline using Java's new HTTP2 support.

In previous versions of Java (Java 8) I was making many calls to a REST server using multiple threads.

I had a global list of parameters and I would go through the parameters to make different sorts of requests.

For example:

String[] params = {"param1","param2","param3" ..... "paramSomeBigNumber"};

for (int i = 0 ; i < params.length ; i++){

   String targetURL= "http://ohellothere.notarealdomain.commmmm?a=" + params[i];

   HttpURLConnection connection = null;

   URL url = new URL(targetURL);
   connection = (HttpURLConnection) url.openConnection();
   connection.setRequestMethod("GET");

   //Send request
   DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

//Do some stuff with this specific http response

}

In the previous code what I would do is construct multiple HTTP requests to the same server with just a little change in the parameter. This took a while to complete so I even would break up the work using threads so that each thread would work on some chunk of the param array.

With HTTP2 I would now not have to create a brand new connection every time. The problem is I do not quite understand how to implement this using the new versions of Java (Java 9 - 11).

If I have an array param as I do previously how would I do the following:

1) Re-use the same connection?
2) Allow different threads to use the same connection?

Essentially I am looking for an example to do what I was doing previously but now utilizing HTTP2.

Regards

Inner answered 1/2, 2019 at 17:46 Comment(0)
S
11

This took a while to complete so I even would break up the work using threads so that each thread would work on some chunk of the param array.

With Java 11's HttpClient, this is actually very simple to achieve; all you need is the following snippet:

var client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();

String[] params = {"param1", "param2", "param3", "paramSomeBigNumber"};

for (var param : params) {
    var targetURL = "http://ohellothere.notarealdomain.commmmm?a=" + param;
    var request = HttpRequest.newBuilder().GET().uri(new URI(targetURL)).build();
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
          .whenComplete((response, exception) -> {
              // Handle response/exception here
          });
}

This uses HTTP/2 to send the request asynchronously and then handles the response String (or Throwable) when it is received in a callback.

Scientism answered 1/2, 2019 at 18:21 Comment(2)
Thanks for the reply! I have tried to run it and it runs but nothing seems to happen. Inside of the "whenComplete" method I added System.out.println(response.statusCode()) and System.out.println(exception.getMessage()); to see what is being returned, but nothing prints out?. I tried using another url: var targetURL = "jsonplaceholder.typicode.com/todos/1" and nothign as well.Inner
The requests are sent asynchronously, and I suspect that your program is exiting before the response is received (since the main thread terminates). To fix this, you can use a custom ExecutorService and block the main thread until the responses are received, or change the code to use send instead, which is blocking and does not use multiple threads.Scientism

© 2022 - 2024 — McMap. All rights reserved.