繁体   English   中英

如何每5秒发送一次HttpPost

[英]How to send HttpPost every 5 secs

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

但它不起作用。

即使我丢失了先前的连接并建立了新的连接以发送第二个连接,第二个execute函数也始终被阻止。

您的问题留下了很多问题,但是可以通过以下方法实现基本要点:

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

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

}

我尝试了您的代码,但出现了异常: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);
}

使用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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM