Java 11: Synchronous HTTP GET into a String 📎
To fetch the content of a website synchronously into a String
:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
...a request has to be constructed with an URI:
var uri = URI.create("https://airhacks.tv");
var request = HttpRequest.newBuilder(uri).GET().build();
...then sent (=executed) with an instance of HttpClient
:
var client = HttpClient.newHttpClient();
String responseBody = client.send(request, BodyHandlers.ofString()).body();
System.out.println(responseBody);