2
我的活动使用AsynTask执行http请求。 如果Web服务器不回答,如何处理HttpResponse? 当前当我的网络服务器关闭时,AsynTask停止在“HttpResponse response = client.execute(httppost);”然后什么都不做。我需要处理这个响应并做一些事情,但是下面的代码“execute”不会被执行。如何在AsyncTask中处理HttpResponse android
这里是纽约后台任务:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
String result = null;
try {
// Add your data
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("session_id", session_id));
postData.add(new BasicNameValuePair("i_key", params[0]));
HttpPost httppost = new HttpPost("http://my.webserver.com/getInfo.php");
httppost.setEntity(new UrlEncodedFormEntity(postData));
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(responseEntity.getContent(),
"UTF-8"));
result = reader.readLine().toString();
} else {
Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show();
}
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return result;
}
如何,如果Web服务器已关闭,没有回答我能处理的响应?
1分钟后您是否超时异常? – Adil 2013-04-21 17:05:14
如果您的网络服务器没有关闭/不回复,请设置超时,之后您将收到超时异常。试一试,http://stackoverflow.com/questions/16098810/access-network-availability-state-android/16099100#16099100 – surender8388 2013-04-21 17:10:27
你不应该使用AsyncTask来执行网络请求,因为当你的设备的方向改变活动被破坏,但也是与此活动的生命周期相关的AsyncTask。为了避免这种情况,应该使用服务模式。 – Pcriulan 2013-04-24 19:43:19