2012-04-23 58 views
0

我試圖從互聯網上讀取一個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; 
} 

} 

但該文件爲空。

+0

你讀過例外嗎?使用後臺線程。 – SLaks 2012-04-23 19:36:20

+1

最好避免主線程上的網絡操作。 – kosa 2012-04-23 19:41:26

+0

檢查這個線程: http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Plutoz 2012-04-23 20:45:40

回答

0

嘗試在AsyncTask內包含網絡呼叫邏輯。

僅供參考,您可以在AsyncTask的doInBackground()方法內做後臺進程。

+0

或擺脫方向改變的問題,去'AsyncTaskLoader' – 2012-04-24 07:17:15

+0

我試圖,我編輯的問題, 請檢查一下 – Edgar 2012-04-24 18:58:53