Android - setSoTimeout not working

前端 未结 3 797
一整个雨季
一整个雨季 2021-01-15 18:56

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). H

相关标签:
3条回答
  • 2021-01-15 19:04

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

    0 讨论(0)
  • 2021-01-15 19:04

    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.

    0 讨论(0)
  • 2021-01-15 19:18

    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:

    • http://code.google.com/p/android/issues/detail?id=2409
    • Http connection timeout on Android not working
    • http connection timeout issues
    • Socket timeout when making HTTPGet requests using DefaultHTTPClient

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

    0 讨论(0)
提交回复
热议问题