Search code examples
java-11java-http-client

Printing blank lines HttpResponse JDK 11


I'm studying the new HttpClient from Java 11 and is not working properly. When I try to print the body from a website the body() method print blank lines:

var httpClient = HttpClient.newHttpClient();        
var request = HttpRequest.newBuilder(URI.create("http://iteratorlearning.com")).build();
HttpResponse<String> response = httpClient.send(request,BodyHandlers.ofString()); 
System.out.println("Printing Body : " + response.body());

Why response.body() doesn't print the content from the body?


Solution

  • If you examine the response status code you will see that it's 301, which is a redirection (moved permanently). By inspecting the response headers you can see that the new location is http://iteratrlearning.com . This is a redirect to a different site, so by default HttpClient will not follow this link (redirect to different sites can often be used for scams).

    You can configure the HttpClient to always follow redirect if you want - but I wouldn't recommend it outside of testing purpose, or when you trust the original site (you can use HttpClient::followRedirect(Redirect.ALWAYS))