处理Android上的gzip压缩内容

时间:2010-10-03 00:20:38

标签: java android gzip

我正在尝试使用DOM方法在Android上解析网络上的文件。

有问题的代码是:

try {
    URL url = new URL("https://www.beatport.com/en-US/xml/content/home/detail/1/welcome_to_beatport");

    InputSource is = new InputSource(url.openStream());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(is);
    document.getDocumentElement().normalize();
} catch(Exception e) {
    Log.v(TAG, "Exception = " + e);
}

但我得到以下例外:

V/XMLParseTest1(  846):Exception = org.xml.sax.SAXParseException: name expected (position:START_TAG <null>@2:176 in java.io.InputStreamReader@43ea4538) 

该文件正在递给我gzipped。我检查了调试器中的is对象,其长度为6733字节(与响应头中文件的内容长度相同)但是,如果我将文件从浏览器保存到我的硬盘驱动器,它的大小是59114字节。此外,如果我将它上传到我自己的服务器,该服务器在服务时没有gzip XML-s并设置URL,代码运行就好了。

我猜测会发生的事情是Android尝试解析gzip压缩流。

有没有办法首先解压缩流?还有其他想法吗?

2 个答案:

答案 0 :(得分:22)

您可以将url.openStream()的结果包装在GZIPInputStream中。例如:

InputSource is = new InputSource(new GZIPInputStream(url.openStream()));

要自动检测何时执行此操作,请使用Content-Encoding HTTP标头。例如:

URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
if ("gzip".equals(connection.getContentEncoding())) {
  stream = new GZIPInputStream(stream));
}
InputSource is = new InputSource(stream);

答案 1 :(得分:3)

  

默认情况下,这个HttpURLConnection实现请求   服务器使用gzip压缩。由于getContentLength()返回   传输的字节数,你不能用那种方法来预测如何   可以从getInputStream()读取许多字节。相反,请阅读   直到它耗尽:当read()返回-1时。 Gzip压缩   可以通过在请求中设置可接受的编码来禁用   头:

     

urlConnection.setRequestProperty(“Accept-Encoding”,“identity”);

所以没必要做。

相关问题