0

我需要从我的 android 应用程序执行一些 HTTP 请求。我根据需要使用 AsyncTask,网络部分在 doInBackground 中。

这是我的请求类:

public class AsyncRequest extends AsyncTask<Void, Integer, HttpResponse>{

private     ProgressDialog  dialog;
private     Activity        activity;
private     HttpUriRequest  query;
private     HttpClient      client;
private     HttpResponse    response;
private     String          dialogMsg;
private     String          uri;

public String getUri() {
    return uri;
}

public void setUri(String uri) {
    this.uri = uri;
}

public AsyncRequest(Activity a, HttpUriRequest q, HttpClient c, String m) {
    query = q;
    client = c;
    activity = a;
    dialog = new ProgressDialog(a);
    dialogMsg = m;
}

@Override
protected void onPostExecute(HttpResponse res) {
    if (dialog.isShowing())
        dialog.dismiss();
}

protected void onPreExecute() {
    this.dialog.setMessage(dialogMsg);
    this.dialog.show();
}

@Override
protected HttpResponse  doInBackground(Void... arg0) {
    try {
        response = client.execute(query);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    return response;
}

protected   HttpResponse    getResponse() {
    return response;
}
}    

而且,在我的 UI 线程中,我以这种方式使用它:

AsyncRequest        request;
    HttpClient          httpClient = new DefaultHttpClient();
    HttpGet             getQuery = new            HttpGet("Here goes my url");
    HttpResponse        response = null;
    String              rt = "Null";
    getQuery.setHeader("Authorization",    getIntent().getExtras().getString("token"));

    request = new AsyncRequest(this, getQuery, httpClient, "Loading events...");
    try {
        response =  request.execute().get(3, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    HttpEntity entity = response.getEntity();
    try {
        rt = EntityUtils.toString(entity);
    } catch (Exception e) {
             e.printStackTrace();
        return ;
    }

所以,我是一个android初学者,但我猜这个异常是在主线程中执行网络相关代码时捕获的。但是我在我的 doInBackground() 方法中运行 client.execute()。是调用execute().get()(在ui线程中)导致问题吗?

4

1 回答 1

2

你有这个

response =  request.execute().get(3, TimeUnit.SECONDS);

调用不再是异步的get()AsyncTask它阻塞等待响应的 ui 线程。这导致NetworkOnMainThreadException.

摆脱get(3, TimeUnit.SECONDS);

只需使用request.execute(). 您可以在onPostExecute. 您还可以使用接口作为 Activity 的回调。

在下面的链接中通过黑带检查答案

如何从 AsyncTask 返回布尔值?

于 2014-03-31T09:08:05.160 回答