jef*_*ffh 5 java xml parsing android httpurlconnection
我有一个奇怪的问题.我收到以下错误导致强制关闭:
org.apache.harmony.xml.ExpatParser $ ParseException:在第1行第0列:在org.apache.harmony.xml的org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:508)中找不到任何元素.位于org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:329)的orat.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:286)中的ExpatParser.parseDocument(ExpatParser.java:467)
单击"强制关闭"按钮后,将重新创建"活动",并且解析完成顺利进行.我在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
Run Code Online (Sandbox Code Playgroud)
为什么活动强制关闭然后立即运行而没有任何问题?BufferedInputStream会有什么不同吗?我很困惑.:(
感谢大家的时间.
更新:事实证明,HttpURLConnection.getResponseCode()经常返回-1,因此可能没有正确设置InputStream.
HTTPURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
Run Code Online (Sandbox Code Playgroud)
那些线有点奇怪.难道HTTPURLConnection还是HttpURLConnection?默认请求方法已经存在GET.setDoOutput(true)然而,它将迫使它POST.
我将替换所有这些行
URLConnection connection = serverAddress.openConnection();
Run Code Online (Sandbox Code Playgroud)
然后重试.它可能会发生错误,因为您强制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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9789 次 |
| 最近记录: |