在http请求android中设置超时

时间:2013-08-13 10:56:18

标签: android httpclient httpresponse

我使用以下代码通过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连接超时中显示文本..我该怎么做 请帮忙

3 个答案:

答案 0 :(得分: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();
   }

答案 1 :(得分:3)

使用此代码完成您的任务

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

答案 2 :(得分:0)

如果您正在使用异步任务,并且该任务位于doinbackground内部,则如果您从该函数更新ui,它将引发错误。因此,请使用以下代码显示吐司。

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