Skip to content

Instantly share code, notes, and snippets.

@swetharnaik
Last active November 26, 2021 16:56
Show Gist options
  • Save swetharnaik/5e030fe077250ae5aca36cf3483713f1 to your computer and use it in GitHub Desktop.
Save swetharnaik/5e030fe077250ae5aca36cf3483713f1 to your computer and use it in GitHub Desktop.
Java 11 - HttpClient example
import java.io.IOException;
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 HttpClientExample {
public static void main(String[] args) throws IOException, InterruptedException {
//supports HTTP2
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest getRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:8080"))
.build();
HttpResponse<String> response = httpClient.send(getRequest,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment