我需要从我的 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线程中)导致问题吗?