我正在尝试下载一个 xml 文件以从服务器解析,但服务器不发送 HTTP 标头,只发送 xml 文本。我已经尝试了几乎所有用我能找到的 URL 下载文件的方法,但一切都给了我一个 I/O 异常。我可以将文件加载到 WebView 中,但我自己无法下载文件。
如何打开连接并下载没有 HTTP 标头的 xml 文件?
编辑:仍然给我一个 I/O 异常,这是我正在使用的代码:
private class UpdateTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void...voids ) {
String url = "http://192.168.1.92/state.xml";
try{
//get XML Pull parser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
//factory.setValidating(false);
XmlPullParser xpp = factory.newPullParser();
HttpGet httpGet = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpGet);
if(response == null) return null;
HttpEntity httpEntity = response.getEntity();
InputStream inStream = null;
StringBuilder sb = null;
if (httpEntity == null) return null;
try {
inStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inStream.close();
} catch (Exception ex) {
}
String xmlString = sb.toString();
xpp.setInput(new StringReader(xmlString));
int eventType = xpp.getEventType();
String name = null;
String text = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) { // <name>
name = xpp.getName();
System.out.println("got name: " + name);
} else if(eventType == XmlPullParser.END_TAG) {// </name> (xpp.getName();
} else if(eventType == XmlPullParser.TEXT) { // <>text</>
text = xpp.getText();
System.out.println("got text: " + text);
}
eventType = xpp.next();
}
finished = true;
}catch(MalformedURLException e){
System.out.println("Malformed URL");
}catch(IOException e){
System.out.println("IO Exception updating " + name + " at address: " + address);
}catch(XmlPullParserException e){
System.out.println("XML Pull Parser Error updating " + name + " at address: " + address);
}catch(Exception e){
}
return null;
}
}
每次都给我一个 I/O 异常。但是,如果我将它指向一个提供 HTTP 标头的服务器,它就可以正常下载。服务器是我们内部制造的设备,当您请求 state.xml 文件时,较旧的设备不提供 HTTP 标头,因此我需要能够同时使用两者。