我需要显示 Http Web 调用超时异常的警报消息。(即)我需要在 android 中的 Web 调用的特定时间段(如 5 秒)内显示“服务器连接超时”之类的警报。我该怎么做?
我的代码:
公共类 MainActivity 扩展 Activity {
static InputStream is = null;
static JSONObject jObj = null;
static HttpClient httpClient;
String json, Token;
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressDialog = ProgressDialog.show(MainActivity .this, "", "Loading...",
true);
new Thread() {
// Run Mehod
@Override
public void run() {
getCC();
messagehandler.sendEmptyMessage(0);
} // End of run
}.start();
}
private Handler messagehandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
progressDialog.dismiss();
String response=json;
//Do steps from response
}
}
};
private void getCC() {
SSLCertificate();
// HttpClient client = new DefaultHttpClient();
String getURL = "My URL";
HttpGet get = new HttpGet(getURL);
get.setHeader("Accept", "*/*,text/xml,application/json");
get.setHeader("Cache-Control", "no-cache");
get.setHeader("Content-type", "application/json");
HttpResponse response;
try {
// defaultHttpClient
response = httpClient.execute(get);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
}
private static void SSLCertificate() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setContentCharset(params, "HTTP.ISO-8859-1");
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(),
443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
schemeRegistry);
HttpConnectionParams.setConnectionTimeout(params, 300);
HttpConnectionParams.setSoTimeout(params, 300);
httpClient = new DefaultHttpClient(params);
httpClient = new DefaultHttpClient(ccm, params);
}
} 谢谢。