Archit Arora
Archit Arora

Reputation: 2626

Polling an Http server (sending http get requests repeatedly) in java

My web server sends some information when a REST call is made to it. I would like to constantly poll this server (send HTTP GET requests repeatedly after an interval of ,say, 5 seconds) to check if there are any changes in the information returned. What is the most efficient way to do this? Can you please provide some code examples?

Please note that I only want to develop the client side code.

I have tried using java's Timer class as follows -

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    public void run() {
        //send HTTP requests
    }
}, 0, 3000); 

I'm not sure if this is an efficient way.

Upvotes: 2

Views: 9101

Answers (2)

Adheep
Adheep

Reputation: 1585

Use ApacheHttpClient or any other REST client framework like Jersey, RestEasy etc to invoke the REST service.

But here I've used ApacheHttpClient to invoke a Rest service and get the response as String

Note: Read about HttpCore and HttpClient

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
  public void run()
  {
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("Your Rest URL");

    //add your headers if needed like this
    httpGet.setHeader("Content-type", "application/xml");
    httpGet.setHeader("Accept", "application/xml");

    HttpResponse response = client.execute(httpGet); 
    HttpEntity httpEntity = response.getEntity();

    //get response as String or what ever way you need
    String response = EntityUtils.toString(httpEntity);
  }
}, 0, 3000); 

Hope it helps!

Upvotes: 4

Eric Stein
Eric Stein

Reputation: 13682

Well, I won't write code, but I will tell you to use a conditional header for your requests. Either If-None-Matches should be sent up with the most recent ETag you got back, or If-Modified-Since should be sent up with the timestamp of your most recent response. That way, if nothing has changed, you get back a 304 Not Modified rather than the whole request body. It will save the server some time, and it means much less wire traffic. You can read RFC 7232 for more information on how they work.

Note that most frameworks do not support conditional headers. Whoever owns the server will probably have to write that code if it does not already exist.

Upvotes: 2

Related Questions