2013-07-05 125 views
0

在Java中,我希望每隔5秒发送一次HttpPost,而不必等待响应。我怎样才能做到这一点?如何每5秒发送一次HttpPost

我使用下面的代码:

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost post = new HttpPost(url); 
StringEntity params = new StringEntity(json.toString() + "\n"); 
post.addHeader("content-type", "application/json"); 
post.setEntity(params); 
httpClient.execute(post); 

Thread.sleep(5000); 

httpClient.execute(post); 

,但它不工作。

即使我失去了以前的连接并建立了一个新的连接发送第二个连接,第二个执行功能始终被阻止。

+0

此代码是否在循环中? – fvrghl

+0

它不起作用不是诊断。 “封锁”和“不起作用”是什么意思? – kolossus

+0

“blocked”的意思是“httpClient.execute(post)”会一直等待数据(或响应),如果不是,它会一直被阻塞,不起作用意味着 - 如果我像这样运行我的程序,将得到异常:java.lang.IllegalStateException:无效的BasicClientConnManager的使用:连接仍然分配。请确保在分配另一个连接之前释放连接。 – user2552010

回答

3

你的问题留下了一大堆的问题,但它的基本点可以通过以下方式实现:

while(true){ //process executes infinitely. Replace with your own condition 

    Thread.sleep(5000); // wait five seconds 
    httpClient.execute(post); //execute your request 

} 
+0

我想我必须在发送新请求之前释放以前的连接。但我不想使用“EntityUtils.consume(entity);”因为如果服务器没有响应,它将始终在“httpClient.execute(post)”中被阻止。 – user2552010

1

我想你的代码,我得到了异常: java.lang.IllegalStateException:使用无效的BasicClientConnManager:连接仍然分配。 确保在分配另一个连接之前释放连接。

此异常已经登录HttpClient 4.0.1 - how to release connection?

我能够通过消耗用下面的代码的响应释放连接:

public void sendMultipleRequests() throws ClientProtocolException, IOException, InterruptedException { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost post = new HttpPost("http://www.google.com"); 
    HttpResponse response = httpClient.execute(post); 

    HttpEntity entity = response.getEntity(); 
    EntityUtils.consume(entity); 

    Thread.sleep(5000); 

    response = httpClient.execute(post); 
    entity = response.getEntity(); 
    EntityUtils.consume(entity); 
} 
+0

根据你的回复,如果服务器不向我的HttpClient发送任何响应,代码“response = httpClient.execute(post);”将始终被阻止,对吧?如果我不想被阻挡,我该怎么办? – user2552010

+0

有什么办法可以每隔5秒发送一次请求并忽略响应(也许没有响应从服务器发回给我)? – user2552010

1

使用DefaultHttpClient是同步的,这意味着程序被阻塞,等待响应。您可以使用async-http-client库来执行异步请求(如果您不熟悉Maven,可以从search.maven.org下载jar文件)。示例代码可能如下所示:

import com.ning.http.client.*; //imports 

try { 
     AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); 

     while(true) { 

      asyncHttpClient 
        .preparePost("http://your.url/") 
        .addParameter("postVariableName", "postVariableValue") 
        .execute(); // just execute request and ignore response 

      System.out.println("Request sent"); 

      Thread.sleep(5000); 
     } 
    } catch (Exception e) { 
     System.out.println("oops..." + e); 
    } 
+0

我尝试了你的代码,但如果没有响应,仍然会被下一个请求阻塞。 – user2552010

+0

你可以发布你测试过的代码吗?它与我的代码完全相同吗?我已经在发布之前对它进行了测试,一切正常。你如何得出程序执行被阻止的结论? –