如何每5秒发送一次HttpPost

时间:2013-07-05 00:50:34

标签: java

在Java中,我想每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);

但它不起作用。

即使我丢失了以前的连接并设置了一个新的连接来发送第二个连接,第二个执行功能总是被阻止。

3 个答案:

答案 0 :(得分:3)

你的问题留下了许多问题,但其基本要点可以通过以下方式实现:

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

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

}

答案 1 :(得分: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);
}

答案 2 :(得分: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);
    }