JDK11 HttpClient example

Small example of how to call out to a URI using Java 11 HttpClient. Nothing new here really. Just for me to remember one day.

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpClient.Version;
import java.time.Duration;

public class Junk {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .followRedirects(Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(20))
        .build();
        HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://crossbrowsertesting.com"))
        .build();
        HttpResponse response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        System.out.println(response);
        System.out.println(response.body());
    }
}

Enter fullscreen mode Exit fullscreen mode

Java docs are here: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html

原文链接:JDK11 HttpClient example

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容