我正在尝试使用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); }
但我得到以下exception:
V/XMLParseTest1( 846):Exception = org.xml.sax.SAXParseException: name expected (position:START_TAG @2:176 in java.io.InputStreamReader@43ea4538)
该文件正在递给我gzipped。 我已经检查了调试器中的is对象,其长度为6733字节(与响应头中文件的内容长度相同)但是如果我将文件从浏览器保存到我的硬盘,则其大小为59114字节。 此外,如果我将它上传到我自己的服务器,它服务时不会gzip XML-s并设置URL代码运行正常。
我猜测会发生什么是Android尝试解析gzip压缩流。
有没有办法先解压缩流? 还有其他想法吗?
您可以将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);
默认情况下,HttpURLConnection的此实现请求服务器使用gzip压缩。 由于getContentLength()返回传输的字节数,因此无法使用该方法来预测可从getInputStream()读取的字节数。 相反,读取该流直到它耗尽:当read()返回-1时。 可以通过在请求标头中设置可接受的编码来禁用Gzip压缩:
urlConnection.setRequestProperty(“Accept-Encoding”,“identity”);
所以没什么必要的。