开发者

Socket timeout when making HTTPGet requests using DefaultHTTPClient

开发者 https://www.devze.com 2023-02-15 18:06 出处:网络
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

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号