android - 在httprequest android中设置超时

标签 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 连接超时中显示文本。我该怎么做 请帮忙

最佳答案

您可以按如下方式进行:

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

关于android - 在httprequest android中设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18207265/

相关文章:

httpresponse - 如何将 apache nifi 流文件添加到 httpresponse 中

java - 通过 Apache Axis 调用安全 URL 时出现无效许可证异常

c# - 如何解析来自 HttpClient 的 JSON 字符串?

android - 在android中使用游标从数据库表中获取数据

Android:列出每个存储桶的缩略图

java - 为什么要为 HttpHead 方法取回 cookie?

php - 使用 PHP 在网页上显示 HTTP 响应

http - 如何使用 boost::http::response_parser 解析字符串?

android - Kiosk 模式和 Fire OS - startLockTask 不工作

android - 转换为 Dalvik 格式失败,错误为 1 :- No solution works