DEV Community

Tony Colston
Tony Colston

Posted on

3 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay