如何让 HttpClient 返回状态码和响应体?

编程入门 行业动态 更新时间:2024-10-12 03:19:14
本文介绍了如何让 HttpClient 返回状态码和响应体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图让 Apache HttpClient 触发 HTTP 请求,然后显示 HTTP 响应代码(200、404、500 等)以及 HTTP 响应正文(文本字符串).需要注意的是,我使用的是 v4.2.2 因为大多数 HttpClient 示例来自 v.3.xx 并且 API 从版本 3 到版本 4 发生了很大变化.

I am trying to get Apache HttpClient to fire an HTTP request, and then display the HTTP response code (200, 404, 500, etc.) as well as the HTTP response body (text string). It is important to note that I am using v4.2.2 because most HttpClient examples out there are from v.3.x.x and the API changed greatly from version 3 to version 4.

不幸的是,我只能让 HttpClient 返回状态代码或响应正文(但不能同时返回).

Unfortunately I've only been able to get HttpClient returning the status code or the response body (but not both).

这是我所拥有的:

// Getting the status code. HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("whatever.blah"); HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); // Getting the response body. HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("whatever.blah"); ResponseHandler<String> handler = new BasicResponseHandler(); String body = client.execute(httpGet, handler);

所以我问:使用 v4.2.2 库,我如何从同一个 client.execute(...) 获取状态代码和响应正文代码> 电话? 提前致谢!

So I ask: Using the v4.2.2 library, how can I obtain both status code and response body from the same client.execute(...) call? Thanks in advance!

推荐答案

不要为 execute 提供处理程序.

Don't provide the handler to execute.

获取HttpResponse对象,使用handler获取body,直接从中获取状态码

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

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

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

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri) .connectTimeout(MILLIS_ONE_SECOND) .socketTimeout(MILLIS_ONE_SECOND) .execute(); HttpResponse httpResponse = response.returnResponse(); StatusLine statusLine = httpResponse.getStatusLine();

对于旧版本的 java 或 httpcomponents,代码可能看起来不同.

For older versions of java or httpcomponents, the code might look different.

更多推荐

如何让 HttpClient 返回状态码和响应体?

本文发布于:2023-11-10 07:07:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!