我使用apache commons http客户端每秒通过post发送数据,有没有办法让下面的代码更有效率?我知道http是无状态的,但是我可以做些什么来改进,因为在这种情况下基本URL总是相同的(只有参数值改变 .
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;
}
2 回答
使用多线程连接管理器,
http://hc.apache.org/httpclient-3.x/threading.html#MultiThreadedHttpConnectionManager
这将改善保持活动并提高每秒连接准备就绪的机会,因此您不必重新 Build TCP连接 .
如果你需要每秒发送一个请求并得到回复,那么是的,这就是你所能做的一切 . 但是,是的,它将使用相当数量的资源 .
另一种需要研究的方法是Comet方法,其中HTTP连接对服务器保持开放,并且信息逐渐通过该连接发送 . Here's an interesting article with examples.