Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Making multiple requests using HTTP2

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

like image 295
user2924127 Avatar asked Feb 01 '19 17:02

user2924127


1 Answers

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.

like image 193
Jacob G. Avatar answered Oct 22 '22 23:10

Jacob G.