0

在 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);

但它不起作用。

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

4

3 回答 3

3

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

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

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

}
于 2013-07-05T00:57:58.940 回答
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);
    }
于 2013-07-05T07:37:47.320 回答
1

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

此异常已记录在HttpClient 4.0.1 - 如何释放连接?

我能够通过使用以下代码使用响应来释放连接:

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);
}
于 2013-07-05T01:57:10.743 回答