从HTTP Android读取XML

时间:2012-04-23 19:33:54

标签: android xml

我正在尝试从互联网上读取xml文件。

这是我正在使用的代码:

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;
}

}

但该文件为空。

1 个答案:

答案 0 :(得分:0)

尝试在AsyncTask

中包含Web调用逻辑

仅供参考,您可以在AsyncTask的doInBackground()方法中进行后台处理。