如何获取字符串形式的 HTTP 响应正文?

发布于 2024-11-03 05:49:29 字数 501 浏览 1 评论 0 原文

我知道曾经有一种方法可以通过 Apache Commons 获取它,如下所示:

http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html

...这里有一个示例:

http://www.kodejava.org/examples/416.html

...但我相信这是已弃用。

有没有其他方法可以在 Java 中发出 http get 请求并以字符串而不是流的形式获取响应正文?

I know there used to be a way to get it with Apache Commons as documented here:

http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html

...and an example here:

http://www.kodejava.org/examples/416.html

...but I believe this is deprecated.

Is there any other way to make an http get request in Java and get the response body as a string and not a stream?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

若沐 2024-11-10 05:49:29

这是我的工作项目中的两个示例。

  1. 使用EntityUtils HttpEntity< /a>

    HttpResponse 响应 = httpClient.execute(new HttpGet(URL));
    HttpEntity实体=response.getEntity();
    字符串responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    

  2. 使用BasicResponseHandler

    HttpResponse 响应 = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    

Here are two examples from my working project.

  1. Using EntityUtils and HttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
  2. Using BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    
谁与争疯 2024-11-10 05:49:29

我能想到的每个库都会返回一个流。您可以使用 IOUtils.toString() 来自 Apache Commons IO 在一个方法调用中将 InputStream 读取到 String 中。例如:

URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

更新:我更改了上面的示例,以使用响应中的内容编码(如果可用)。否则,它会默认为 UTF-8 作为最佳猜测,而不是使用本地系统默认值。

Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

Update: I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.

天涯沦落人 2024-11-10 05:49:29

这是我正在使用 Apache 的 httpclient 库处理的另一个简单项目的示例:

String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

只需使用 EntityUtils 来获取字符串形式的响应正文。很简单。

Here's an example from another simple project I was working on using the httpclient library from Apache:

String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

just use EntityUtils to grab the response body as a String. very simple.

仅冇旳回忆 2024-11-10 05:49:29

这在特定情况下相对简单,但在一般情况下相当棘手。

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));

答案取决于 Content-Type HTTP 响应标头

该标头包含有关有效负载的信息,并且可能定义文本数据的编码。即使您假设文本类型,您也可能需要检查内容本身才能确定正确的字符编码。 例如,请参阅 HTML 4 规范 了解详细信息关于如何针对特定格式执行此操作。

一旦编码已知,InputStreamReader 可用于解码数据。

这个答案取决于服务器是否做正确的事情 - 如果您想处理响应标头与文档不匹配的情况,或者文档声明与所使用的编码不匹配的情况,那就是另一回事了。< /em>

This is relatively simple in the specific case, but quite tricky in the general case.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));

The answer depends on the Content-Type HTTP response header.

This header contains information about the payload and might define the encoding of textual data. Even if you assume text types, you may need to inspect the content itself in order to determine the correct character encoding. E.g. see the HTML 4 spec for details on how to do that for that particular format.

Once the encoding is known, an InputStreamReader can be used to decode the data.

This answer depends on the server doing the right thing - if you want to handle cases where the response headers don't match the document, or the document declarations don't match the encoding used, that's another kettle of fish.

荒人说梦 2024-11-10 05:49:29

下面是使用 Apache HTTP 客户端库以字符串形式访问响应的简单方法。

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//... 

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);

Below is a simple way of accessing the response as a String using Apache HTTP Client library.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//... 

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);
留一抹残留的笑 2024-11-10 05:49:29

麦克道尔的答案是正确的。但是,如果您尝试上面几篇文章中的其他建议。

HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}

然后它会给你非法状态异常,指出内容已经被消耗。

The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.

HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}

Then it will give you illegalStateException stating that content is already consumed.

无悔心 2024-11-10 05:49:29

就这个怎么样?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));

How about just this?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));
明媚如初 2024-11-10 05:49:29

这是一个普通的 Java 答案:

import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;

...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(targetUrl)
  .header("Content-Type", "application/json")
  .POST(BodyPublishers.ofString(requestBody))
  .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();

Here is a vanilla Java answer:

import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;

...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(targetUrl)
  .header("Content-Type", "application/json")
  .POST(BodyPublishers.ofString(requestBody))
  .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();
世界如花海般美丽 2024-11-10 05:49:29

我们还可以使用下面的代码来获取java中的HTML响应

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();
    //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse
    HttpGet request1 = new HttpGet(args[0]);
    HttpResponse response1 = client.execute(request1);
    int code = response1.getStatusLine().getStatusCode();

    try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
        // Read in all of the post results into a String.
        String output = "";
        Boolean keepGoing = true;
        while (keepGoing) {
            String currentLine = br.readLine();

            if (currentLine == null) {
                keepGoing = false;
            } else {
                output += currentLine;
            }
        }

        System.out.println("Response-->" + output);
    } catch (Exception e) {
        System.out.println("Exception" + e);

    }
}

We can use the below code also to get the HTML Response in java

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();
    //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse
    HttpGet request1 = new HttpGet(args[0]);
    HttpResponse response1 = client.execute(request1);
    int code = response1.getStatusLine().getStatusCode();

    try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
        // Read in all of the post results into a String.
        String output = "";
        Boolean keepGoing = true;
        while (keepGoing) {
            String currentLine = br.readLine();

            if (currentLine == null) {
                keepGoing = false;
            } else {
                output += currentLine;
            }
        }

        System.out.println("Response-->" + output);
    } catch (Exception e) {
        System.out.println("Exception" + e);

    }
}
蒗幽 2024-11-10 05:49:29

这是一种轻量级的方法:

String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) { 
    responseString +=
    Character.toString((char)response.getEntity().getContent().read()); 
}

当然 responseString 包含网站的响应,并且响应是 HttpResponse 类型,由 HttpClient.execute(request)

Here's a lightweight way to do so:

String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) { 
    responseString +=
    Character.toString((char)response.getEntity().getContent().read()); 
}

With of course responseString containing website's response and response being type of HttpResponse, returned by HttpClient.execute(request)

你穿错了嫁妆 2024-11-10 05:49:29

以下代码片段显示了将响应正文作为字符串处理的更好方法,无论它是 HTTP POST 请求的有效响应还是错误响应:

BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}       
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:

BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}       
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}
隱形的亼 2024-11-10 05:49:29

如果您使用 Jackson 反序列化响应正文,一个非常简单的解决方案是使用 request.getResponseBodyAsStream() 而不是 request.getResponseBodyAsString()

If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream() instead of request.getResponseBodyAsString()

养猫人 2024-11-10 05:49:29

使用 Apache commons Fluent API,可以按如下方式完成:

String response = Request.Post("http://www.example.com/")
                .body(new StringEntity(strbody))
                .addHeader("Accept","application/json")
                .addHeader("Content-Type","application/json")
                .execute().returnContent().asString();

Using Apache commons Fluent API, it can be done as mentioned below,

String response = Request.Post("http://www.example.com/")
                .body(new StringEntity(strbody))
                .addHeader("Accept","application/json")
                .addHeader("Content-Type","application/json")
                .execute().returnContent().asString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文