Reputation:
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; }
Upvotes: 6
Views: 3141
Reputation: 75456
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.
Upvotes: 3
Reputation: 51052
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.
Upvotes: 1