1

So I'm running into a not working socket timeout. I followed all instructions given by existing posts, but its still not working (I never get a socket timeout exception). Here is my code:

AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
   @Override
   protected String doInBackground(String... params) {
      String location = params[0];

      try {
         HttpGet httpGet = new HttpGet(location);
         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 = 0;
         HttpConnectionParams.setConnectionTimeout(httpParameters,
               timeoutConnection);

         // Set the default socket timeout (SO_TIMEOUT)
         // in milliseconds which is the timeout for waiting for data.
         int timeoutSocket = 2000;
         HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

         DefaultHttpClient client = new DefaultHttpClient(httpParameters);
         Log.d(this.getClass().getSimpleName(), "STARTING CLIENT!!! ");
         HttpResponse response = client.execute(httpGet);
         Log.d(this.getClass().getSimpleName(), "CLIENT CANCELLED!!! ");

         if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            return new Scanner(out.toString()).useDelimiter("\\A").next();
         } else {
            return "";
         }
      } catch (IOException e) {
         e.printStackTrace();
         return null;
      } catch (URISyntaxException e) {
         e.printStackTrace();
         return null;
      }
   }

   @Override
   protected void onPostExecute(String result) {
      try {
         // doStuff
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
};
task.execute(location);

So I should get a socket timeout exception after two seconds, but the client is just ignoring that. Any help?

Thanks in advance


So here is all of the code:

public void fetch(String location) {    
    AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            String location = params[0];

            try {
                HttpGet httpGet = new HttpGet(location);
                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 = 0;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 2000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                DefaultHttpClient client = new DefaultHttpClient(httpParameters);
                Log.d(this.getClass().getSimpleName(), "STARTING CLIENT!!! ");
                HttpResponse response = client.execute(httpGet);
                Log.d(this.getClass().getSimpleName(), "CLIENT CANCELLED!!! ");

                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    return new Scanner(out.toString()).useDelimiter("\\A").next();
                } else {
                    return "";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (URISyntaxException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                //doStuff
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    task.execute(location);
}
Tim Post
  • 32,782
  • 15
  • 106
  • 168
user1416721
  • 21
  • 2
  • 4

3 Answers3

2

A while back I had similar problems. I've experimented a bit and noticed that when I ran my app in the emulator the timeouts didn't work and when I ran it on a real device it did work. I've tested it with the DefaultHttpClient, HttpUrlConnection and AndroidHttpClient, all three showed the same results; an IOexception (UnknownHostException) after about 20 seconds in the emulator regardless of any set timeout.

Googling revealed that other people have also reported problems with timeout:

None of the proposed solutions worked for me, so I guess the only reliable solution is to manage timeouts yourself.

Community
  • 1
  • 1
THelper
  • 14,855
  • 6
  • 61
  • 97
0

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".

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 = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);

itsrajesh4uguys
  • 4,560
  • 3
  • 19
  • 31
  • hi @ user1416721 i have added new code. it is working for me . i have used two days ago. worked fine . use it and let me know. – itsrajesh4uguys May 25 '12 at 07:22
  • 1
    no, still not working. the client starts to execute and never finishes in less than 5 secs and no SocketTimeoutException is thrown... Maybe it has something to do that I'm using it in doInBackground as AsyncTask? – user1416721 May 25 '12 at 07:35
  • so when i disable the internet connection "client cancelled" is never reached. after about 5-10 secs i get an ioexception. but i want to get the sockettimeoutexception first... Log.d(this.getClass().getSimpleName(), "STARTING CLIENT!!! "); HttpResponse response = client.execute(httpGet); Log.d(this.getClass().getSimpleName(), "CLIENT CANCELLED!!! "); – user1416721 May 25 '12 at 07:46
  • if you need more code or information let me know. I'm struggling with this problem for 6 hours now – user1416721 May 25 '12 at 08:35
  • Yeah kindly post more code. i will test it myself and then let u know – itsrajesh4uguys May 25 '12 at 09:58
0

See: https://stackoverflow.com/a/20031077/2609238

The problem might be in the Apache HTTP Client. See HTTPCLIENT-1098. Fixed in 4.1.2.

The timeout exception tries to reverse DNS the IP, for logging purposes. This takes an additional time until the exception is actually fired.

Community
  • 1
  • 1
noam
  • 101
  • 1
  • 5