代码之家  ›  专栏  ›  技术社区  ›  janosrusiczki

在Android上处理gzip内容

  •  9
  • janosrusiczki  · 技术社区  · 14 年前

    我正在尝试使用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);
    }
    

    但我有以下例外:

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

    文件正被提交给我gzip。我查过了 is 调试程序中的对象,其长度为6733字节(与响应头中文件的内容长度相同),但是,如果从浏览器将文件保存到硬盘驱动器,则其大小为59114字节。此外,如果我将它上传到我自己的服务器上,当它为XML-S提供服务时,该服务器没有gzip XML-S,并且设置了URL,那么代码就可以正常运行。

    我猜发生的事情是Android试图解析gzip流。

    有没有办法先解压这条河?还有其他想法吗?

    2 回复  |  直到 11 年前
        1
  •  22
  •   Laurence Gonsalves    14 年前

    您可以包装的结果 url.openStream() 在一个 GZIPInputStream . 如:

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

    要自动检测何时执行此操作,请使用内容编码HTTP头。如:

    URLConnection connection = url.openConnection();
    InputStream stream = connection.getInputStream();
    if ("gzip".equals(connection.getContentEncoding())) {
      stream = new GZIPInputStream(stream));
    }
    InputSource is = new InputSource(stream);
    
        2
  •  3
  •   itindex    12 年前

    默认情况下,此httpurlConnection的实现请求 服务器使用gzip压缩。因为getContentLength()返回 传输的字节数,不能使用该方法预测 可以从getinputstream()中读取许多字节。相反,读一下 流,直到耗尽:当read()返回-1时。gzip压缩 可以通过在请求中设置可接受的编码来禁用 页眉:

    urlconnection.setrequestproperty(“接受编码”,“标识”);

    所以没什么需要做的。