我想使用JDOM从URL解析XML文件.但是在尝试这个时:
SAXBuilder builder = new SAXBuilder();
builder.build(aUrl);
Run Code Online (Sandbox Code Playgroud)
我得到这个例外:
Invalid byte 1 of 1-byte UTF-8 sequence.
Run Code Online (Sandbox Code Playgroud)
我认为这可能是BOM问题.所以我查看了源代码并在文件开头看到了BOM.我尝试使用aUrl.openStream()Commons IO BOMInputStream从URL读取和删除BOM .但令我惊讶的是它没有检测到任何BOM.我尝试从流中读取并写入本地文件并解析本地文件.我将InputStreamReader和OutputStreamWriter的所有编码设置为UTF8但是当我打开文件时它有疯狂的字符.
我认为问题在于源URL编码.但是当我在浏览器中打开URL并将XML保存在文件中并通过上述过程读取该文件时,一切正常.
我对此问题的可能原因表示感谢.
该 HTTP 服务器以 GZIPped 形式发送内容(如果您不知道这意味着什么,Content-Encoding: gzip请参阅http://en.wikipedia.org/wiki/HTTP_compressionaUrl.openStream() ),因此您需要包装一个GZIPInputStream将为您解压缩的内容。例如:
builder.build(new GZIPInputStream(aUrl.openStream()));
Run Code Online (Sandbox Code Playgroud)
编辑添加,基于后续评论:如果您事先不知道URL是否会被GZIPped,您可以编写如下内容:
private InputStream openStream(final URL url) throws IOException
{
final URLConnection cxn = url.openConnection();
final String contentEncoding = cxn.getContentEncoding();
if(contentEncoding == null)
return cxn.getInputStream();
else if(contentEncoding.equalsIgnoreCase("gzip")
|| contentEncoding.equalsIgnoreCase("x-gzip"))
return new GZIPInputStream(cxn.getInputStream());
else
throw new IOException("Unexpected content-encoding: " + contentEncoding);
}
Run Code Online (Sandbox Code Playgroud)
(警告:未经测试)然后使用:
builder.build(openStream(aUrl.openStream()));
Run Code Online (Sandbox Code Playgroud)
。这基本上与上面的相同 -aUrl.openStream()被明确记录为简写aUrl.openConnection().getInputStream()- 除了它Content-Encoding在决定是否将流包装在GZIPInputStream.