在Android中设置HTTP请求超时时间

5
我正在使用以下代码通过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个回答

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();
   }

我怎么知道超时发生了...我的意思是说...如果超时,我想打印一条消息“检查您的连接”,我该怎么做? - Saurabh Sinha
1
你可以捕获 ConnectTimeoutException。 - Ritesh Gune

3
请使用这段代码来完成您的任务。
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);

我怎么知道超时发生了...我的意思是说...如果超时,我想打印一条消息“检查您的连接”,我该怎么做? - Saurabh Sinha

0
如果您正在使用异步任务,并且它位于doinbackground中,则如果您从该函数更新UI,它将抛出错误。因此,请使用以下代码显示toast。
runOnUiThread(new Runnable() { public void run() { } });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接