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.
精彩评论