2010-06-15 89 views
3

我使用apache commons http客户端通过post发送数据每秒钟,有没有办法让下面的代码更有效率?我知道HTTP是无状态的,但有什么我可以做,以改善因为基础URL总是在这种情况下(仅参数值变化相同。apache commons http客户端效率

 
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

看起来很好。你有没有理由另有想法? – skaffman 2010-06-15 18:33:39

回答

1

如果您需要发送一个请求,并得到一个每秒响应,然后是的,这就是所有你可以做的,但是,是的,它会使用相当数量的资源。服务器和信息将通过该连接逐渐发送。Here's an interesting article with examples.

+2

每秒一个HTTP请求不算什么 - 它几乎无法证明Comet,IMO。 – skaffman 2010-06-15 19:06:26

+0

用户不会问他/她是否不在意。更好地了解选项。 – 2010-06-15 19:08:03

+0

不错的选择,我会阅读关于彗星 – user157195 2010-06-15 20:17:45