I have created the following function for checking the connection status:
private void checkConnectionStatus() {
HttpClient httpClient = new DefaultHttpClient();
try {
String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
+ strSessionString + "/ConnectionStatus";
Log.d("phobos", "performing get " + url);
HttpGet method = new HttpGet(new URI(url));
HttpResponse response = httpClient.execute(method);
if (response != null) {
String result = getResponse(response.getEntity());
...
When I shut down the server for testing the execution waits a long time at line
HttpResponse response = httpClient.execute(method);
Does anyone know how to set the timeout in order to avoid waiting too long?
Thanks!
An option is to use the OkHttp client, from Square.
Add the library dependency
In the build.gradle, include this line:
Where
x.x.x
is the desired library version.Set the client
For example, if you want to set a timeout of 60 seconds, do this way:
ps: If your minSdkVersion is greater than 8, you can use
TimeUnit.MINUTES
. So, you can simply use:For more details about the units, see TimeUnit.
In my example two timeouts are set. The connection timeout throws "java.net.SocketTimeoutException: Socket is not connected" and the socket timeout "java.net.SocketTimeoutException: The operation timed out".
If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().
If you're using the default http client, here's how to do it using the default http params:
Original credit goes to http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/
you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.