我在AsyncTask innerc类中创建以下方法以连接到Internet并从提供的URL获取JSON文件。如果连接错误,我遇到问题,我的应用程序会挂起很长时间等待连接......
private JSONArray connectAndCreateJsonArray(String url) {
JSONArray jsonArray = new JSONArray();
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("Cache-Control", "no-cache");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
jsonArray = new JSONArray(stringBuilder.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonArray;
}
我从doInBackground()方法调用此方法。如何使用AlertDialog处理连接超时?
答案 0 :(得分:1)
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
TimeOut,直到建立连接
int timeOutInMillis = 10*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeOutInMillis);
设置timeOut直到收到数据
int socketTimeOutinMillis = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOutinMillis);
使用参数
创建客户端DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
答案 1 :(得分:0)
我猜你试图在你的主线程上连接互联网,导致你的应用程序挂起。为您的连接生成一个单独的线程。您可以捕获超时异常并在相应的catch块中显示toast或alertdialog
catch(TimeoutException e){
String error = e.getMessage();
e.printStackTrace();
boolean errorflag=true;
return error ;
在postexecute中显示用户此异常