java - 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
.
问候
解决方案
这需要一段时间才能完成,所以我什至会使用线程来分解工作,以便每个线程都可以处理参数数组的某些块。
使用 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
)时处理它。
推荐阅读
- java - Java spring 请求头太大
- c++ - 有人能告诉我为什么我们在 C++ 中对 int 变量和 pow() 求和时会得到错误的答案吗?
- sql - SQL REGEXP - 查找包含字符串的所有用户
- ios - Swift 协议:我可以限制关联类型吗?
- arrays - 关于 Chip Pearson 的 ReverseArrayInPlace 函数,用户首先如何将数组传递给输入函数?
- python - Python应用程序到一个文件.exe,编译后应用程序将无法运行
- java - 实现只在前台运行的定时器
- bazel - Bazel:src 不在 genrule 上执行
- html - 使文本背景颜色不继承 CSS
- python - 错误:“浮动”对象不可下标