Created
November 11, 2019 16:08
-
-
Save thomasdarimont/b1c8cb0ea6e2591abf558dd533531970 to your computer and use it in GitHub Desktop.
Java 11 HttpClient example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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