简体   繁体   中英

How to send HttpPost every 5 secs

In a Java, I want to send HttpPost every 5 secs without waiting for the response. How can I do that?

I use the following code:

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

but it does not work.

Even though I lose the previous connection and set up a new connection to send the second, the second execute function is always blocked.

Your question leaves a bunch of questions, but the basic point of it can be achieved by:

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

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

}

I tried your code and I got the exception : java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated. Make sure to release the connection before allocating another one.

This exception is already logged in HttpClient 4.0.1 - how to release connection?

I was able to release the connection by consuming the response with the following code:

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

Using DefaultHttpClient is synchronous which means that program is blocked waiting for the response. Instead of that you could use async-http-client library to perform asynchronous requests (you can download jar files from search.maven.org if you're not familiar with Maven). Sample code may look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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