在java中轮询Http服务器(重复发送http get请求) [英] Polling an Http server (sending http get requests repeatedly) in java

查看:2784
本文介绍了在java中轮询Http服务器(重复发送http get请求)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web服务器在对其进行REST调用时发送一些信息。我想不断轮询这个服务器(在一段时间,比如5秒后重复发送HTTP GET请求),以检查返回的信息是否有任何变化。
最有效的方法是什么?
你能提供一些代码示例吗?

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.

我尝试过使用java的Timer类,如下所示 -

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

我不确定这是否有效。

推荐答案

使用 ApacheHttpClient 或任何其他REST客户端框架(如Jersey,RestEasy等)来调用REST服务。

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

但是我在这里使用ApacheHttpClient来调用Rest服务并以String的形式获得响应

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

注意:了解HttpCore和HttpClient

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

希望有所帮助!

这篇关于在java中轮询Http服务器(重复发送http get请求)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆