java服务器 轮询,在java中轮询Http服务器(重复发送http get请求)

该博客探讨了如何通过使用Apache HttpClient来定期轮询RESTful服务以检查信息更新。作者提出了一种使用Java Timer类结合HttpClient实现每5秒发送一次HTTP GET请求的方法,并询问这是否是最有效的方式。解决方案建议使用HttpClient来调用REST服务,获取响应并将其转换为字符串,以实现高效的轮询机制。
摘要由CSDN通过智能技术生成

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值