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.
解决方案
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!