处理Android上的gzip压缩内容

jan*_*zki 9 java android gzip

我正在尝试使用DOM方法在Android上解析Web上的文件.

有问题的代码是:

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);
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下异常:

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

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

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

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

Lau*_*ves 22

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

InputSource is = new InputSource(new GZIPInputStream(url.openStream()));
Run Code Online (Sandbox Code Playgroud)

要自动检测何时执行此操作,请使用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);
Run Code Online (Sandbox Code Playgroud)