展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

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();
        }
    }
    
}
posted @ 2022-08-26 08:05  DogLeftover  阅读(239)  评论(0编辑  收藏  举报