0

我正在尝试从互联网上读取一个 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;
}

}

但该文件为空。

4

1 回答 1

0

尝试在AsyncTask.

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

于 2012-04-24T07:10:47.493 回答