1

I am building an Android app that will fire multiple HTTP requests (say a request every second) to a server to fetch data. What are the best practices I must follow?

Should I create and close the client after each request, like the following?

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity(json.toString());
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.close();
}

Or should I create a client initially, use it for all requests and then finally close it when I'm done with it?

John Bupit
  • 10,406
  • 8
  • 39
  • 75
  • You may want to use https://github.com/square/okhttp instead – Karioki Dec 18 '14 at 13:21
  • Thanks for the library. Again, should I maintain a single OKHTTP client throughout a session or should I create a new one for each request? – John Bupit Dec 18 '14 at 13:34
  • Okhttp support Connection pooling so it solve your problem without extra coding at your side. and its getting updated according to good approaches to your problem. – Karioki Dec 18 '14 at 13:37
  • My goal IS to write my own library, hence the question. I'll look into okhttp though. Thanks. – John Bupit Dec 18 '14 at 13:39

1 Answers1

1

The idea of closing your HttpClient is about releasing the allocated ressources. Therefore, It depends on how often you plan on firing those HTTP requests.

Keep in mind that firing a request every 10 seconds is considered an eternity ;)

Alex. P.
  • 133
  • 9
  • Say I have 1 request a second. Should I pool the connections, or just one connection is enough? Is there a possiblity that the connection expires or something like that? – John Bupit Dec 18 '14 at 13:41
  • I believe the default HTTP connection timeout is set to 60 seconds. You can check the value using System.out.println(httpget.getParams().getParameter("http.socket.timeout")); You can also set that attribute to the value you need. Refer to http://hc.apache.org/httpclient-3.x/preference-api.html – Alex. P. Dec 18 '14 at 15:24