views:

141

answers:

2

I use apache commons http client to send data via post every second, is there a way to make the following code more efficient? I know http is stateless, but is there anything I can do to improve since the base url is always the same in this case(only the parameter value change.

private void sendData(String s){ 
      try
         {
              HttpClient client = getHttpClient();


              HttpPost method = new HttpPost("http://192.168.1.100:8080/myapp");
              System.err.println("send to server "+s);
              List formparams = new ArrayList();
              formparams.add(new BasicNameValuePair("packet", s));

              UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
              method.setEntity(entity);

              HttpResponse resp=client.execute(method);
              String res = EntityUtils.toString(resp.getEntity());
              System.out.println(res);

         }
         catch (Exception e)
         {
              e.printStackTrace();

         }
    }
 private HttpClient getHttpClient() {
  if(httpClient==null){
   httpClient = new DefaultHttpClient();
  }
  return httpClient;
 }
+1  A: 

If you need to send a request and get a response each second, then yeah, that's about all you can do. However, yes, it will use a fair amount of resources.

Another approach to look into is the Comet approach, in which an HTTP connection is left open to the server and information is gradually sent over that connection. Here's an interesting article with examples.

JacobM
One HTTP request per second is nothing - it hardly justifies Comet, IMO.
skaffman
The user wouldn't have asked if he/she wasn't concerned. Better to know what the options are.
JacobM
nice alternative,I will read about Comet
+1  A: 

Use a multi-threaded connection manager,

http://hc.apache.org/httpclient-3.x/threading.html#MultiThreadedHttpConnectionManager

This will improve the keep-alive and improve the chance that your connection is ready every second so you don't have to reestablish the TCP connection.

ZZ Coder
nice pointer, I might not be able to use this class since I'm running on android SDK which supports limited version of apache commons http client.