0

使用以下代码发出获取请求时:

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

不管怎么说,还是要谢谢你!

4

1 回答 1

2

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

InputStreamReader isReader = new InputStreamReader(stream, "UTF-8"); 
于 2014-04-11T15:11:56.813 回答