Jdk11使用HttpClient提交Http2请求的实现方法
Http2协议的强制要求https,如果⽬标URI是HTTP的,则⽆法使⽤HTTP 2协议
测试 -> https://http2.akamai.com/demo
判断⽹站是否是http2协议
浏览器 -> network⾯板 -> 右键名称 -> 选择protocol
浏览器 -> network⾯板 -> 右键名称 -> 选择协议
- 发送http2请求案例
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
testHttp2();
}
private static final String targetUrl = "https://http2.akamai.com/demo";
private static final URI uri = URI.create(targetUrl);
private static final void testHttp2() {
//设置建立连接的超时 connect timeout
var httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(5000))
.version(HttpClient.Version.HTTP_2)
.build();
var request = HttpRequest.newBuilder().timeout(Duration.ofMillis(3000))
.header("key1", "v1")
.header("key2", "v2")
.uri(uri).build();
try {
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
System.out.println(response.version());
} catch (Exception e) {
e.printStackTrace();
}
}
}
到此这篇关于jdk11使用HttpClient提交Http2请求的文章就介绍到这了,更多相关Jdk11 Http2请求内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章