gpt4 book ai didi

java - HttpURLConnection 响应不正确

转载 作者:行者123 更新时间:2023-12-02 05:56:45 25 4
gpt4 key购买 nike

当使用下面的代码发出 get 请求时:

private String get(String inurl, Map headers, boolean followredirects) throws MalformedURLException, IOException {

URL url = new URL(inurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(followredirects);

// Add headers to request.
Iterator entries = headers.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
connection.addRequestProperty((String)key, (String)value);
}

// Attempt to parse
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
BufferedReader br = new BufferedReader(isReader );
System.out.println(br.readLine());

// Disconnect
connection.disconnect();

return connection.getHeaderField("Location");
}

得到的响应完全是无意义的(例如 ��:ks�6��﯐9�rђ� e��u�n�qש�v��"uI*�W��s)

但是我可以在 Wireshark 中看到响应是 HTML/XML,与上面的字符串完全不同。我尝试了多种不同的方法来解析 InputStream,但每次都得到相同的结果。

请注意:只有当它是 HTML/XML 时才会发生这种情况,纯 HTML 才有效。

为什么响应会以这种格式返回?

提前致谢!

===已解决===

嗯,明白了!

服务器在包含 XML 时压缩响应,因此我需要使用 GZIPInputStream 而不是 InputSream。

GZIPInputStream stream = new GZIPInputStream(connection.getInputStream());

无论如何,谢谢!

最佳答案

在输入流中使用 UTF-8 编码,如下所示

InputStreamReader isReader = new InputStreamReader(stream, "UTF-8"); 

关于java - HttpURLConnection 响应不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016239/

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