我想下載一個xml文件來從服務器解析,但服務器不發送HTTP頭文件,只是xml文本。我已經嘗試了幾乎所有使用我可以找到的URL下載文件的方法,但所有內容都給我一個I/O異常。我可以將文件加載到WebView中,但我無法自行下載文件。如何從服務器上下載沒有http頭的xml文件
如何打開連接並下載沒有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標頭,因此我需要能夠使用這兩個標頭。
查找/閱讀一些關於如何提問的文章。你的問題應該儘可能具體。您應該儘可能多地提供有關問題的信息。 – Maxim
如果您向瀏覽器提供http://192.168.1.92/state.xml並返回xml,請在try部分的第一行放置一個斷點,並找出導致該異常的原因或在此處發佈您的LogCat – Maxim
瀏覽器返回xml頁面正常。 iOS也連接並加載正常,而WebViews也顯示XML。在代碼中,當我打開一個InputStream時,它會拋出一個I/O異常,或者在這種情況下,當我執行client.execute(httpGet);我的logcat只是返回System.out.println(「I/O異常」);即使有嚴格的模式。有沒有辦法獲得更詳細的錯誤報告? – daven3t