【问题标题】:HttpURLConnection response is incorrectHttpURLConnection 响应不正确
【发布时间】:2014-04-11 15:05:57
【问题描述】:

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

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

还是谢谢!

【问题讨论】:

  • 您使用的是哪种编码?注意:切勿在未指定编码的情况下使用InputStreamReader
  • @Kayaman 我已经尝试指定 UTF-8,但这没有任何区别。
  • 那你看错了wireshark框架。 GZip 编码的流量应该看起来像你的“废话”数据。

标签: java xml parsing httpurlconnection inputstreamreader


【解决方案1】:

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

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

【讨论】:

  • 此外,它看起来一点也不像 UTF-8。它可能是 UTF-16。
猜你喜欢
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 2021-05-31
  • 2016-04-03
  • 1970-01-01
  • 2020-11-03
相关资源
最近更新 更多