首页 > 解决方案 > Java - 使用 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.

问候

标签: javahttp2java-11

解决方案


这需要一段时间才能完成,所以我什至会使用线程来分解工作,以便每个线程都可以处理参数数组的某些块。

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

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


推荐阅读