Java - 使用 HTTP2 发出多个请求

Java - Making multiple requests using HTTP2

我无法找到任何很好的示例来概述使用 Java 的新 HTTP2 支持。

在 Java (Java 8) 的早期版本中,我使用多线程多次调用 REST 服务器。

我有一个全局参数列表,我会通过这些参数来发出不同类型的请求。

例如:

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

}

在前面的代码中,我要做的是构造多个 HTTP 对同一服务器的请求,只需稍微更改参数即可。这需要一段时间才能完成,所以我什至会使用线程分解工作,以便每个线程都可以在参数数组的某个块上工作。

有了 HTTP2,我就不用每次都创建新的连接了。问题是我不太明白如何使用 Java (Java 9 - 11) 的新版本来实现它。

如果我像以前一样有一个数组参数,我将如何执行以下操作:

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

基本上我正在寻找一个例子来做我以前做的事情,但现在使用 HTTP2.

此致

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.

用Java11的HttpClient,这个实现起来其实很简单;您只需要以下代码段:

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
          });
}

这使用 HTTP/2 异步发送请求,然后在回调中收到响应时处理响应 String(或 Throwable)。