Java - 使用HTTP2发出多个请求

use*_*127 6 java http2 java-11

我没有找到任何很好的例子来概述使用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

}
Run Code Online (Sandbox Code Playgroud)

在前面的代码中,我要做的是HTTP只需对参数进行一点改动即可构建对同一服务器的多个请求.这需要一段时间才能完成,所以我甚至会使用线程分解工作,这样每个线程都可以在param数组的一些块上工作.

随着HTTP2我现在就不必每次都创建一个全新的连接.问题是我不太明白如何使用新版本的Java(Java 9 - 11)来实现它.

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

1) Re-use the same connection?
2) Allow different threads to use the same connection?
Run Code Online (Sandbox Code Playgroud)

基本上我正在寻找一个例子来做我以前做过但现在正在使用的东西HTTP2.

问候

Jac*_* G. 9

这需要一段时间才能完成,所以我甚至会使用线程分解工作,这样每个线程都可以在param数组的一些块上工作.

使用Java 11 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
          });
}
Run Code Online (Sandbox Code Playgroud)

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

  • 请求是异步发送的,我怀疑你的程序在收到响应之前就已退出(因为主线程终止).要解决此问题,您可以使用自定义`ExecutorService`并阻止主线程直到收到响应,或者更改代码以使用`send`代替,这是阻塞并且不使用多个线程. (3认同)