在http请求android中设置超时

问题描述 投票:5回答:3

我使用以下代码从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){
            ...
            }

它工作正常。但如果手机连接到wifi或gprs 3g但互联网不工作或互联网连接不存在,我想使用上述代码中的超时功能。

说3秒后我想显示超时请再试一次..我该怎么做。在超时的情况下,我想在textviw连接超时中显示一个文本..我该怎么做,请帮助

android httpclient httpresponse
3个回答
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();
   }

3
投票

使用此代码完成您的任务

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);

0
投票

如果你正在使用异步任务并且它在doinbackground内部,那么如果你更新ui形式该函数它会抛出错误。所以请使用下面的代码来展示吐司。

runOnUiThread(new Runnable() { public void run() { } });

© www.soinside.com 2019 - 2024. All rights reserved.