Java 在Android上处理Gzip内容
我正在尝试使用DOM方法在Android上解析来自web的文件 有关守则是:Java 在Android上处理Gzip内容,java,android,gzip,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 = DocumentBui
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)
V/XMLParseTest1(846):Exception=org.xml.sax.SAXParseException:name应为(位置:java.io中的START_TAG@2:176)。InputStreamReader@43ea4538)
文件正在交给我。我已经在调试器中检查了是
对象,它的长度是6733字节(与响应头中文件的内容长度相同),但是如果我从浏览器将文件保存到硬盘,它的大小是59114字节。此外,如果我把它上传到我自己的服务器上,当它为它们服务时,它不会gzip XML-s并设置URL,那么代码就可以正常运行
我猜Android会尝试解析Gzip流
有没有办法先解压缩流?还有其他想法吗?您可以将
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压缩
可以通过在请求中设置可接受的编码来禁用
标题:
setRequestProperty(“接受编码”、“标识”)
所以不需要做什么。非常感谢。还有一个问题:有没有办法确定流是否被gzip压缩?请查看此链接。这里介绍了一种压缩和解压缩方法。
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
if ("gzip".equals(connection.getContentEncoding())) {
stream = new GZIPInputStream(stream));
}
InputSource is = new InputSource(stream);