HttpURLConnection响应不正确

时间:2014-04-11 15:05:58

标签: java xml parsing httpurlconnection inputstreamreader

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

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

由此产生的反应完全没有意义(例如:k:ks 6 9 rђ e u n qש v “uI * W s)

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

请注意:只有在HTML / XML,纯HTML工作时才会发生这种情况。

为什么回复会以这种格式回复?

提前致谢!

===已解决===

Gah,明白了!

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

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

非常感谢!

1 个答案:

答案 0 :(得分:2)

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

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