如何阅读HttpURLConnection的完整回复?

And*_*zej 18 java httpurlconnection

我在andorid中创建一些修改http标头的代理服务器,它工作正常,但我必须将完整响应转发到'顶层'.
我如何从HttpURLConnection读取整个响应(所有标题,内容,所有内容)?

HttpURLConnection httpURLConnection;
URL url = new URL(ADDRESS);
httpURLConnection = (HttpURLConnection) url.openConnection();
// add headers, write output stream, flush
if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK)
{
    Map<String, List<String>> map = httpURLConnection.getHeaderFields();
    System.out.println("Printing Response Header...\n");

    for (Map.Entry<String, List<String>> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
    }

    return new DataInputStream(httpURLConnection.getInputStream());
}
Run Code Online (Sandbox Code Playgroud)

在getInputStream中我只收到内容,可能有一些整个reposne的流?

Sot*_*lis 29

使用the HttpURLConnection无法直接转储完整的HTTP响应,但您可以使用其各种方法来重建它.例如,

HttpURLConnection httpURLConnection;
URL url = new URL("http://www.google.com");
httpURLConnection = (HttpURLConnection) url.openConnection();
StringBuilder builder = new StringBuilder();
builder.append(httpURLConnection.getResponseCode())
       .append(" ")
       .append(httpURLConnection.getResponseMessage())
       .append("\n");

Map<String, List<String>> map = httpURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
    if (entry.getKey() == null) 
        continue;
    builder.append( entry.getKey())
           .append(": ");

    List<String> headerValues = entry.getValue();
    Iterator<String> it = headerValues.iterator();
    if (it.hasNext()) {
        builder.append(it.next());

        while (it.hasNext()) {
            builder.append(", ")
                   .append(it.next());
        }
    }

    builder.append("\n");
}

System.out.println(builder);
Run Code Online (Sandbox Code Playgroud)

版画

200 OK
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Date: Tue, 07 Jan 2014 16:06:45 GMT
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
X-XSS-Protection: 1; mode=block
Expires: -1
Alternate-Protocol: 80:quic
Set-Cookie: NID=67=OIu8_xhcxE-UPCSfIoTINvRyOe4ALVhIqan2NUI6LMdRkSJHTPGvNkYeYE--WqPSEPK4c4ubvmjWGUyFgXsa453KHavX9gUeKdzfInU2Q25yWP3YtMhsIhJpUQbYL4gq; expires=Wed, 09-Jul-2014 16:06:45 GMT; path=/; domain=.google.ca; HttpOnly, PREF=ID=4496ed99b812997d:FF=0:TM=1389110805:LM=1389110805:S=jxodjb3UjGJSZGaF; expires=Thu, 07-Jan-2016 16:06:45 GMT; path=/; domain=.google.ca
Content-Type: text/html; charset=ISO-8859-1
Server: gws
Cache-Control: private, max-age=0
Run Code Online (Sandbox Code Playgroud)

然后,您也可以获取InputStream并打印其内容.

  • @Error如果未建立连接,它如何获得响应(代码,标头,正文)?不,这段代码显然可以建立连接,只是在内部调用getInputStream()的getResponseCode()调用中隐式地进行了连接。 (2认同)

Gre*_*reg 6

当我寻找类似的问题时,起初对我来说并不明显,所以我找到了解决方案。

阅读身体反应:

readFullyAsString(connection.getInputStream(), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

这来自:https : //stackoverflow.com/a/10505933/1281350

public String readFullyAsString(InputStream inputStream, String encoding) throws IOException {
        return readFully(inputStream).toString(encoding);
    }

    private ByteArrayOutputStream readFully(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, length);
        }
        return baos;
    }
Run Code Online (Sandbox Code Playgroud)

  • 这并不能完全回答问题。问题是如何获得包括 HTTP 标头在内的完整响应。这只是回答如何读取 InputStream 的简单部分。 (2认同)
  • 请参阅此处了解适用于 Java 8 的单行解决方案:/sf/answers/3196167061/ (2认同)