簡體   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