Sau*_*nha 5 android httpresponse httpclient
我使用以下代码从http请求获取服务器的数据.
HttpClient client = new DefaultHttpClient();
String URL = urlGenerator();
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
...
}
Run Code Online (Sandbox Code Playgroud)
它工作正常.但如果手机连接到wifi或gprs 3g但互联网不工作或互联网连接不存在,我想在上面的代码中使用超时功能.
说3秒后我想显示超时请再试一次..我该怎么做.在超时的情况下,我想在textviw连接超时中显示一个文本..我该怎么做,请帮助
Rit*_*une 14
你可以这样做:
try{
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 6000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
} catch (ConnectTimeoutException e) {
//Here Connection TimeOut excepion
Toast.makeText(xyz.this, "Your connection timedout", 10000).show();
}
Run Code Online (Sandbox Code Playgroud)
使用此代码来完成您的任务
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17732 次 |
| 最近记录: |