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

编程入门 行业动态 更新时间:2024-10-28 22:26:14
本文介绍了在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请求)

本文发布于:2023-10-09 16:35:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器   中轮询   java   http   Http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!