我需要从我的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线程中)导致问题吗?
答案 0 :(得分:2)
你有这个
response = request.execute().get(3, TimeUnit.SECONDS);
调用get()
使AsyncTask
不再异步。它阻止ui线程等待响应。这会导致NetworkOnMainThreadException
。
摆脱get(3, TimeUnit.SECONDS);
只需使用request.execute()
即可。您可以在onPostExecute
中更新ui。您还可以使用interface作为Activity的回调。
通过以下链接检查黑带的答案