【问题标题】:Parse RSS from URLs gives me "Invalid byte 2 of 2-byte UTF-8 sequence"从 URL 解析 RSS 给了我“2 字节 UTF-8 序列的无效字节 2”
【发布时间】:2016-12-15 17:21:38
【问题描述】:

我正在尝试操作 RSS 内容并使用 Java 将其转换为 JSON 对象。我使用的来源是:

http://rss.uol.com.br/feed/economia.xmlhttp://g1.globo.com/dynamo/pr/parana/rss2.xml

首先,我尝试了这样的事情:

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(myUrl);
//working with doc variable...

第二个网址可以正常工作(我认为是因为它上面有<?xml version="1.0" encoding="utf-8"?>)。但是第二个失败了

2 字节 UTF-8 序列的字节 2 无效

所以,我尝试做这样的事情:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);

InputStream is = new ByteArrayInputStream(myUrl.getBytes());
Reader reader = new InputStreamReader(is, "UTF-8");
InputSource io = new InputSource(reader);

io.setEncoding("UTF-8");
Document doc = dbf.newDocumentBuilder().parse(io);
//working with doc variable...

但是现在第二个网址给了我这个错误:

prolog 中不允许有内容

虽然第一个仍然给我同样的旧错误。

如何从它的 URL 读取 RSS 文件而不出现任何字符集错误?

【问题讨论】:

  • 在您的第二个代码中,您试图提供 URL,就好像它是实际数据一样。不是。
  • 基本上,第一个 URL 提供了无效的 XML - 第 5 行,Ú 编码不正确。
  • 我知道,但我无法更改 XML,因为它是一个外部文件。
  • 我建议你然后告诉无效文件的来源。如果他们修复它,每个人都会受益。
  • 它是巴西最大的网站之一。那时我觉得我太小了......

标签: java xml utf-8 rss


【解决方案1】:

这对我有用 (JavaSE 8)

String uri="http://rss.uol.com.br/feed/economia.xml";   
URL myUrl=new URL(uri);

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);

//If you do not need a proxy:
//InputStream is=myUrl.openStream();

//I needed a proxy: 
java.net.Proxy pxy =new java.net.Proxy( java.net.Proxy.Type.HTTP,new java.net.InetSocketAddress("apoderado-externo",8080));
URLConnection urlConn=myUrl.openConnection(pxy);
urlConn.connect();
InputStream is =urlConn.getInputStream();


//Prepare to parse the stuff 
Reader reader = new InputStreamReader(is, "UTF-8");
InputSource io = new InputSource(reader);

io.setEncoding("UTF-8");
Document doc = dbf.newDocumentBuilder().parse(io);
//working with doc variable...

我认为不仅 xml 不提供编码,而且 HTTP 标头“内容类型”似乎也不存在。也许BOM也不存在....

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 2013-08-14
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2018-12-10
    • 2012-07-04
    相关资源
    最近更新 更多