簡體   English   中英

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請求,只需對參數進行一些更改。 這需要一段時間才能完成,所以我甚至會使用線程分解工作,這樣每個線程都可以在param數組的一些塊上工作。

使用HTTP2我現在不必每次都創建一個全新的連接。 問題是我不太明白如何使用新版本的Java( Java 9 - 11 )來實現它。

如果我像以前一樣有一個數組參數,我將如何執行以下操作:

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

基本上我正在尋找一個例子來做我以前做過但現在使用HTTP2

問候

這需要一段時間才能完成,所以我甚至會使用線程分解工作,這樣每個線程都可以在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
          });
}

這使用HTTP / 2異步發送請求,然后在回調中接收響應時處理響應String (或Throwable )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM