亲宝软件园·资讯

展开

Jdk11 Http2请求

chniny 人气:0

测试 -> https://http2.akamai.com/demo

浏览器 -> network⾯板 -> 右键名称 -> 选择protocol
浏览器 -> network⾯板 -> 右键名称 -> 选择协议

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();
        }
    }
    
}

加载全部内容

相关教程
猜你喜欢
用户评论