【问题标题】:set timeout in httprequest android在httprequest android中设置超时
【发布时间】:2013-08-13 10:56:17
【问题描述】:

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


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

    • 我怎么知道发生了超时..我的意思是说..如果超时我想打印一条消息“检查您的连接”我该怎么做
    • 你可以捕获 ConnectTimeoutException。
    【解决方案2】:

    使用此代码完成您的任务

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

    【讨论】:

    • 我怎么知道发生了超时..我的意思是说..如果超时我想打印一条消息“检查您的连接”我该怎么做
    【解决方案3】:

    如果您正在使用异步任务并且它位于 doinbackground 中,那么如果您从该函数更新 ui,它将引发错误。所以请使用下面的代码来显示吐司。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多