3

What are the pros and cons behind reusing DefaultHTTPClient when sending HTTP requests from an Android app to an external server? I tried using reusing a DefaultHTTPClient when making periodic HTTPGet requests, but I get random socket timeouts (specially when using 3G).

My code looks like follows:

public class MyHTTPSender {
  private DefaultHTTPClient mClient;

  public MyHTTPSender() {
    mClient = new DefaultHTTPClient();
  }

  public void send(String httpAddress) {
HttpGet get = new HttpGet(this.surrogateURL);
    HttpResponse response = null;
try {
      response = httpClient.execute(get);
      // ... consume entity if OK          
    } catch (Exception e) {
    } finally {
        if (response != null) {
           // do some sanity checks to ensure Entity is there!
           response.getEntity().consumeContent();
        }
    }
  }
}

I can't see anything wrong with what I am doing. I have a separate handler that make HTTPPost requests, and that works perfectly well (uses a different DefaultHTTPClient object).

Any suggestions?

Thira
  • 1,555
  • 1
  • 13
  • 24
  • I'm starting to see the same behavior, beginning with Android 2.3.3. My app worked perfectly before, but now, after upgrading to 2.3.3, I sometimes get java.net.SocketException: Connection timed out. I have 20 seconds socket timeout and connection timeout. – Catalin Morosan Mar 12 '11 at 14:07

1 Answers1

1

What API level are you on?

If you're on 8 or above you might consider trying AndroidHttpClient, which may have a better socket timeouts specified.

Otherwise, you might examine how you're creating the DefaultHttpClient and try specifying longer timeouts.

Matthew
  • 44,826
  • 10
  • 98
  • 87
  • I am using API level 7. I can manually setup the timeout value using something like: httpget.getParams().setParameter("http.socket.timeout", new Integer(5000)); But that still doesn't explain why the time out happens in the first place. Logging at the server shows the GET request was never received. However, when I send a POST request soon after, it is successfully received by the server! – Thira Mar 10 '11 at 02:11