zLupim
zLupim

Reputation: 339

Java HTTP request read response body

How can I read the body of a HTTP request?. I was searching for a simple way and I think this is the easiest.

URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
  /* Now read the retrieved document from the stream. */
  ...
} finally {
  is.close();
}

But how can i read this or print errors in the console? Is there an easier way to make the request and read the response body?

Upvotes: 0

Views: 2591

Answers (2)

Java_Herobrine
Java_Herobrine

Reputation: 60

If you use Java 9+,you can use HttpClient,HttpRequest and HttpResponse.

HttpClient client=HttpClient.newHttpClient();
HttpRequest request=HttpRequest.newBuilder().uri(new URI(your url)).GET().build();
HttpResponse<String> response=client.send(request,BodyHandlers.ofString());
System.out.println(response.body());

Upvotes: 1

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

how can i read this or print in the console please

Use BufferedReader and try with resources:

URL url = new URL("http://www.y.com/url");
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
    br.lines().forEach(System.out::println);
}

Upvotes: 1

Related Questions