我試圖從互聯網上讀取一個xml文件。從HTTP讀取XML Android
這是我使用的代碼:
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mypage.com/version.xml");
HttpResponse resp = client.execute(httppost);
,我得到這個前:
android.os.NetworkOnMainThreadException
我想在答案之後用異步方法做到這一點。 這是我試過的代碼:
public class Download extends AsyncTask<String, Void, Document> {
@SuppressWarnings("unused")
private Exception exception;
public Document document;
public Download(String url)
{
this.execute(url);
}
@Override
protected Document doInBackground(String... url) {
try {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(response.getEntity().getContent());
return document;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
} catch (Exception e) {
exception = e;
return null;
}
}
protected void onPostExecute(Document doc)
{
// TODO: check this.exception
// TODO: do something with the feed
document = doc;
}
}
但該文件爲空。
你讀過例外嗎?使用後臺線程。 – SLaks 2012-04-23 19:36:20
最好避免主線程上的網絡操作。 – kosa 2012-04-23 19:41:26
檢查這個線程: http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Plutoz 2012-04-23 20:45:40