Set timeout in httproquest android

I use the following code to get data from a server with an 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 performance. But if the phone is connected to Wi-Fi or gprs 3g, but the Internet does not work or the Internet connection does not exist, I want to use the timeout function in the above code.

let's say after 3 seconds I want to show a timeout, try again .. how to do it. in case of timeout I want to show the text in the timeout of the textviw connection .. how do I do this please help

+4
source share
2 answers

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

use this code to accomplish your task

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

Source: https://habr.com/ru/post/1496768/


All Articles