要检查您是否可以访问互联网,您可以使用类似的东西
public boolean connesso() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
对于连接超时,我使用 httpclient 来发出请求,您也可以处理套接字超时
HttpParams httpParameters = new BasicHttpParams();
int timeout1 = 1000*10;
int timeout2 = 1000*10;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout1);
HttpConnectionParams.setSoTimeout(httpParameters, timeout2);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
String jsonString = "";
HttpGet request;
try {
request = new HttpGet(new URI(url));
request.addHeader("User-Agent", "Android");
HttpResponse response = httpclient.execute(request);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
jsonString = out.toString();
}
}catch(ConnectException e){
// handle your exception here, maybe something like
Toast.makeText(context,"Error!",5000).show();
finish(); // if your are within activity class, otherwise call finish on your activity
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject myJsonObject = new JSONObject(jsonString);
// etc...