首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何每隔5秒发送一次HttpPost

如何每隔5秒发送一次HttpPost
EN

Stack Overflow用户
提问于 2013-07-05 08:50:34
回答 3查看 2.2K关注 0票数 0

在Java中,我希望每隔5秒发送一次HttpPost,而不等待响应。我该怎么做呢?

我使用以下代码:

代码语言:javascript
复制
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函数总是被阻塞。

EN

回答 3

Stack Overflow用户

发布于 2013-07-05 08:57:59

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

代码语言:javascript
复制
while(true){ //process executes infinitely. Replace with your own condition

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

}
票数 3
EN

Stack Overflow用户

发布于 2013-07-05 09:57:11

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

此异常已记录在HttpClient 4.0.1 - how to release connection?

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

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2013-07-05 15:37:47

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

代码语言:javascript
复制
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);
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17479705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档