set timeout in httprequest android

情到浓时终转凉″ 提交于 2019-12-21 05:04:58

问题


I am using the following code to get data from the server with http request.

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){
            ...
            }

Its working fine.But in case if the phone is connected to wifi or gprs 3g but internet is not working or internet connection is not there, i want to use the timeout feature in the above code.

say after 3 sec i want to show timeout please try again.. how do i do that. in case of time out i want to show a text in the textviw connection timeout .. how do i do that please help


回答1:


You can do it as follows:

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



回答2:


use this code to accomplish your task

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



回答3:


if you are using async task and it is inside doinbackground then it will throw error if you update ui form that function. So kindly use the below code for showing toast .

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



来源:https://stackoverflow.com/questions/18207265/set-timeout-in-httprequest-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!