loading...

JDK11 HttpClient example

tonetheman profile image Tony Colston ・1 min read

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

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

Posted on by:

tonetheman profile

Tony Colston

@tonetheman

wanna be gamedev ... all around nerd and dev

Discussion

pic
Editor guide