android gzip压缩流程,处理Android上的gzip压缩内容

本文探讨了解决Android上使用DOM方法解析被GZIP压缩的XML文件的问题。通过检查异常错误并调整输入源,成功实现了对压缩流的正确解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

所以没什么必要的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值