5

我有一个奇怪的问题。我收到以下导致强制关闭的错误:

org.apache.harmony.xml.ExpatParser$ParseException:在第 1 行,第 0 列:在 org.apache.harmony.xml 的 org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:508) 中找不到元素。 ExpatParser.parseDocument(ExpatParser.java:467) 在 org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:329) 在 org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:286)

单击“强制关闭”按钮后,将重新创建 Activity,并且解析顺利完成。我在 AsyncTask 的 doInBackground 中使用以下代码片段:

URL serverAddress = new URL(url[0]);

HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();

InputStream stream = connection.getInputStream();

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

XMLReader xr = sp.getXMLReader();

xr.parse(new InputSource(stream));  // The line that throws the exception

为什么 Activity 会强制关闭然后立即运行而没有任何问题?BufferedInputStream 会有什么不同吗?我很困惑。:(

谢谢大家的时间。

更新:事实证明 HttpURLConnection.getResponseCode() 经常返回 -1,因此 InputStream 可能没有正确设置。

4

6 回答 6

6
HTTPURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);

这些线条有点奇怪。是HTTPURLConnection还是HttpURLConnection?默认请求方法已经是GET. 然而,这setDoOutput(true)将迫使它POST

我会将所有这些行替换为

URLConnection connection = serverAddress.openConnection();

并重试。它可能会返回错误,因为您强制POST并且没有向输出(请求正文)写入任何内容。顺便说一句,connection.connect()它已经隐式调用了connection.getInputStream(),因此该行也是多余的。

更新:以下用于测试目的是否有效?

BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
    System.out.println(line);
}
reader.close();
于 2010-04-26T19:13:31.153 回答
2

我不知道你是否解决了这个问题,但我遇到了同样的问题。很奇怪,它在模拟器中可以正常工作,但是在电话上,它总是给我xr.parse()错误。即使我打印了它,InputStream它也会给我 xml 文档的合法输出。似乎问题出在InputSource对象的创建中

以下是我修复它的方法:我没有使用直接从 url 字符串创建输入源InputStream来创建你的输入源。InputSource

InputSource a =  new InputSource(url_string);   

其中 url_string 只是一个带有您的 url 的字符串。不要问我为什么它会起作用......我真的不喜欢它,因为没有办法检查超时和类似的事情。但它有效,让我知道它是怎么回事!

于 2010-04-27T17:48:14.510 回答
1

根据InputStreamjavadoc,该方法将阻塞,直到数据可用或遇到 EOF。因此,Socket 的另一端需要关闭它——然后 inStream.read() 调用将返回。

如果使用BufferedReader,则可以逐行阅读。该readLine()方法将在读取 HTTP 响应中的一行后立即返回。

于 2010-04-26T19:07:53.413 回答
1

在相关的设计说明中,加载 URL 的内容永远不应强制关闭活动 - 我建议将所有这些放入 AsyncTask 实现中,并在您返回 GUI 线程后报告或重试。

于 2010-04-26T20:06:15.760 回答
1

即使我面临同样的问题。我首先使用InputStreaminScanner来打印它的内容。然后尝试在 XML 解析器中传递它。

问题是我没有关闭Scanner对象。并使用Inputstreamin 解析器。

关闭扫描仪对象后,我能够解决这个问题。

于 2016-12-08T06:01:27.340 回答
0

I ran into the same problem and could make no sense of it because I was parsing directly from the InputSource. When I modified the code to pull the result into a string before the xml parse, I found out the problem was simply a mispelled web service method name and that the error message reported by that service was the killer.

于 2010-09-17T18:12:47.113 回答