Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将HTTP响应主体作为字符串获取?_Java_Apache Httpclient 4.x_Apache Commons - Fatal编程技术网

Java 如何将HTTP响应主体作为字符串获取?

Java 如何将HTTP响应主体作为字符串获取?,java,apache-httpclient-4.x,apache-commons,Java,Apache Httpclient 4.x,Apache Commons,我知道以前有一种方法可以通过Apache Commons获得它,如下所述: …这里有一个例子: …但我认为这是不可取的 有没有其他方法可以在Java中发出http get请求并将响应体作为字符串而不是流获取?我能想到的每个库都返回一个流。您可以使用from在一个方法调用中将InputStream读入字符串。例如: URL url = new URL("http://www.example.com/"); URLConnection con = url.openConnection(); In

我知道以前有一种方法可以通过Apache Commons获得它,如下所述:

…这里有一个例子:

…但我认为这是不可取的


有没有其他方法可以在Java中发出http get请求并将响应体作为字符串而不是流获取?

我能想到的每个库都返回一个流。您可以使用from在一个方法调用中将
InputStream
读入
字符串。例如:

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作为最佳猜测,而不是使用本地系统默认值。

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

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));
答案取决于
内容类型

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

一旦知道了编码,就可以使用一个编码来解码数据


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

下面是我使用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);
}
String响应=新字符串();
List nameValuePairs=新的ArrayList(1);
添加(新的BasicNameValuePair(“j”,请求));
HttpEntity requestEntity=新的UrlEncodedFormEntity(nameValuePairs);
HttpPost HttpPost=新的HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse HttpResponse=mHttpClient.execute(httpPost);
HttpEntity responseEntity=httpResponse.getEntity();
if(responseEntity!=null){
response=EntityUtils.toString(responseEntity);
}
只需使用EntityUtils将响应主体作为字符串抓取即可。非常简单。

就这个怎么样

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

下面是我工作项目中的两个例子

  • 使用及

  • 使用


  • 麦克道尔的答案是正确的。然而,如果你在上面的几个帖子中尝试其他建议

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

    然后它将给您illegalStateException,说明内容已被使用。

    下面是一种使用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);
    
    import org.apache.http.HttpResponse;
    导入org.apache.http.client.HttpClient;
    导入org.apache.http.client.ResponseHandler;
    导入org.apache.http.client.methods.HttpGet;
    导入org.apache.http.impl.client.BasicResponseHandler;
    //... 
    HttpGet;
    HttpClient-HttpClient;
    //初始化上面的变量
    ResponseHandler ResponseHandler=新BasicResponseHandler();
    String responseBody=httpClient.execute(get,responseHandler);
    
    我们也可以使用下面的代码来获取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);
    
        }
    }
    

    以下是一种轻量级的方法:

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

    当然
    responseString
    包含网站的响应,响应类型为
    HttpResponse
    ,由
    HttpClient.execute(请求)返回

    以下是代码片段,它显示了将响应正文作为字符串处理的更好方法,无论它是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;
        }
    }
    

    您可以使用发送Http请求并处理响应的三维参与方库。著名的产品之一是ApacheCommonsHttpClient:。迄今为止,还有一个知之甚少但简单得多的HTTPClient(我编写的开源MgntUtils库的一部分):、。使用这两个库中的任何一个,您都可以独立于Spring发送REST请求和接收响应,作为业务逻辑的一部分

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

    以下是一个普通的Java答案:

    导入java.net.http.HttpClient;
    导入java.net.http.HttpResponse;
    导入java.net.http.HttpRequest;
    导入java.net.http.HttpRequest.bodypublisher;
    ...
    HttpClient=HttpClient.newHttpClient();
    HttpRequest请求=HttpRequest.newBuilder()
    .uri(targetUrl)
    .header(“内容类型”、“应用程序/json”)
    .POST(bodypublisher.ofString(requestBody))
    .build();
    HttpResponse response=client.send(请求,HttpResponse.BodyHandlers.ofString());
    字符串responseString=(字符串)response.body();
    
    使用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();
    

    在许多情况下,这会损坏文本,因为该方法使用系统默认文本编码,该编码因操作系统和用户设置而异。@McDowell:oops谢谢,我将该方法的javadoc与编码链接,但在示例中忘记使用它。现在我在示例中添加了UTF-8,虽然技术上应该使用响应中的
    内容编码
    头(如果可用)。IOUtils的使用非常好。很好的实用方法。实际上,字符集是在contentType中指定的,比如“charset=…”,而不是在contentEncoding中指定的,它包含类似“gzip”的内容。这个函数会导致输入流关闭,有没有办法@WhiteFang34我可以打印我的响应并继续使用http实体方法1面临的唯一问题是,当您执行
    response.getEntity()
    时,实体对象将被使用,现在它可以作为
    responseString
    使用。如果您再次尝试执行response.getEntity(),它将返回
    IllegalStateException
    。在我的情况下有效-从
    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;
        }
    }
    
    String response = Request.Post("http://www.example.com/")
                    .body(new StringEntity(strbody))
                    .addHeader("Accept","application/json")
                    .addHeader("Content-Type","application/json")
                    .execute().returnContent().asString();