简体   繁体   English

Java HTTP 请求读取响应体

[英]Java HTTP request read response body

How can I read the body of a HTTP request?.如何阅读 HTTP 请求的正文? 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?有没有更简单的方法来发出请求并阅读响应正文?

how can i read this or print in the console please请问如何在控制台中阅读或打印

Use BufferedReader and try with resources:使用BufferedReader并尝试使用资源:

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

If you use Java 9+,you can use HttpClient , HttpRequest and HttpResponse .如果你使用 Java 9+,你可以使用HttpClientHttpRequestHttpResponse

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM