Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created November 11, 2019 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/b1c8cb0ea6e2591abf558dd533531970 to your computer and use it in GitHub Desktop.
Save thomasdarimont/b1c8cb0ea6e2591abf558dd533531970 to your computer and use it in GitHub Desktop.
Java 11 HttpClient example
package demo.example;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.header("Accept", "text/html")
.GET()
.build();
var client = HttpClient.newHttpClient();
var asString = HttpResponse.BodyHandlers.ofString();
HttpResponse<String> response = client.send(request, asString);
var statusCode = response.statusCode();
System.out.printf("### Status Code: %s%n", statusCode);
var headers = response.headers();
System.out.printf("### Response Headers: %s%n", headers);
System.out.println("### Body:");
System.out.println(response.body());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment