gpt4 book ai didi

java - 如何读取来自 HttpURLConnection 的完整响应?

转载 作者:太空狗 更新时间:2023-10-29 22:32:50 25 4
gpt4 key购买 nike

我在 andorid 中做了一些修改 http header 的代理服务器,它工作正常,但我必须将完整的响应转发给“顶层”。
我如何从 HttpURLConnection 读取整个响应(所有 header 、内容、一切)?

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

在 getInputStream 中,我只接收到内容,是否可能有一些具有完整响应的流?

最佳答案

无法直接使用 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);

打印

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

然后您可以获得 InputStream 并打印其内容。

关于java - 如何读取来自 HttpURLConnection 的完整响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20976013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com