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 连接超时中显示一个文本.. 我该怎么做,请帮忙

4

3 回答 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();
   }
于 2013-08-13T11:01:07.240 回答
3

使用此代码完成您的任务

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
于 2013-08-13T10:58:55.167 回答
0

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

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

于 2018-08-30T05:53:30.313 回答