100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Java http响应状态码_如何获得HttpClient返回状态码和响应正文?

Java http响应状态码_如何获得HttpClient返回状态码和响应正文?

时间:2023-05-22 16:07:38

相关推荐

Java http响应状态码_如何获得HttpClient返回状态码和响应正文?

小编典典

不要向提供处理程序execute。

获取HttpResponse对象,使用处理程序获取主体并直接从中获取状态代码

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

final HttpGet httpGet = new HttpGet(GET_URL);

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {

StatusLine statusLine = response.getStatusLine();

System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());

String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

System.out.println("Response body: " + responseBody);

}

}

对于快速的单次调用,流利的API很有用:

Response response = Request.Get(uri)

.connectTimeout(MILLIS_ONE_SECOND)

.socketTimeout(MILLIS_ONE_SECOND)

.execute();

HttpResponse httpResponse = response.returnResponse();

StatusLine statusLine = httpResponse.getStatusLine();

对于Java或httpcomponents的旧版本,代码可能看起来有所不同。

-09-15

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。