Preferred Java way to ping a HTTP Url for availability
I need a monitor class that regularly checks whether a given HTTP URL is available. I can take care of the "regularly" part using the Spring TaskExecutor abstraction, so that's not the topic here. The Question is:What is the preferred way to ping a URL in java?
Here is my current code as a starting point:
- package org.javalobby.tnt.net;
- import java.io.IOException;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- public class DnsTest {
- public static void main(String[] args) {
- String url = "http://www.baidu.com";
- try{
- final URLConnection connection = new URL(url).openConnection();
- connection.connect();
- System.out.println("Service " + url + " available, yeah!");
- } catch(final MalformedURLException e){
- throw new IllegalStateException("Bad URL: " + url, e);
- } catch(final IOException e){
- System.out.println("Service " + url + " unavailable, oh no! " + e);
- }
- }
- }
- Is this any good at all (will it do what I want?)
- Do I have to somehow close the connection?
- I suppose this is a GET request. Is there a way to send HEAD instead?
Is this any good at all (will it do what I want?)
You can do so. Another feasible way is using java.net.Socket
.
- url = "www.baidu.com";
- Socket socket = null;
- boolean reachable = false;
- try {
- socket = new Socket(url, 80);
- reachable = true;
- System.out.println("true");
- } finally {
- if (socket != null) try { socket.close(); } catch(IOException e) {}
- }
There's also the InetAddress#isReachable()
:
- boolean reachable = InetAddress.getByName(hostname).isReachable();
This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.
Do I have to somehow close the connection?
No, you don't explicitly need. It's handled and pooled under the hoods.
I suppose this is a GET request. Is there a way to send HEAD instead?
You can cast the obtained URLConnection
to HttpURLConnection
and then use setRequestMethod()
to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. But, those are pretty rare cases.
Update as per the comments: connecting a host only informs if the host is available, not if the content is available. You seem to be more interested in the content since it can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. So you'd like to determine the HTTP response code.
- url = "http://www.baidu.com";
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setRequestMethod("HEAD");
- int responseCode = connection.getResponseCode();
- if (responseCode != 200) {
- // Not OK.
- System.out.println("Not Ok");
- }
- // < 100 is undetermined.
- // 1nn is informal (shouldn't happen on a GET/HEAD)
- // 2nn is success
- // 3nn is redirect
- // 4nn is client error
- // 5nn is server error
For more detail about response status codes see RFC 2616 section 10. Calling connect()
is by the way not needed if you're determining the response data. It will implicitly connect.
For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:
- /**
- * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
- * the 200-399 range.
- * @param url The HTTP URL to be pinged.
- * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
- * the total timeout is effectively two times the given timeout.
- * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
- * given timeout, otherwise <code>false</code>.
- */
- public static boolean ping(String url, int timeout) {
- url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.
- try {
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setConnectTimeout(timeout);
- connection.setReadTimeout(timeout);
- connection.setRequestMethod("HEAD");
- int responseCode = connection.getResponseCode();
- return (200 <= responseCode && responseCode <= 399);
- } catch (IOException exception) {
- return false;
- }
- }
Preferred Java way to ping a HTTP Url for availability的更多相关文章
- java.net.MalformedURLException: Illegal character in URL
在进行接口测试时,意外发现返回结果报java.net.MalformedURLException: Illegal character in URL,意思是“在URL中的非法字符”,我的参数是经过ba ...
- URL中增加BASE64加密的字符串引起的问题(java.net.MalformedURLException:Illegal character in URL)
序 昨天在做一个 Demo 的时候,因为是调用第三方的接口,採用的是 HTTP 的通信协议,依照文档上的说明,须要把參数进行加密后增加到 URL 中.可是,就是这个看似普普通通的操作,却让我着实费了非 ...
- 无法解析db.properties,spring报错:Caused by: java.sql.SQLException: unkow jdbc driver : ${url}
db.properties中配置了url等jdbc连接属性: driver=org.sqlite.JDBCurl=jdbc:sqlite:D:/xxx/data/sqliteDB/demo.dbuse ...
- java匹配http或https的url的正则表达式20180912
package org.jimmy.autosearch20180821.test; import java.util.regex.Matcher; import java.util.regex.Pa ...
- JAVA提取字符串中所有的URL链接,并加上a标签
工具类 Patterns.java 1 package com.util; 2 3 import java.util.regex.Matcher; 4 import java.util.regex.P ...
- Java魔法堂:URI、URL(含URL Protocol Handler)和URN
一.前言 过去一直搞不清什么是URI什么是URL,现在是时候好好弄清楚它们了!本文作为学习笔记,以便日后查询,若有纰漏请大家指正! 二.从URI说起 1. 概念 URI(Uniform Reso ...
- java基础:网络编程TCP,URL
获取域名的两种方法: package com.lanqiao.java.test; import java.net.InetAddress;import java.net.UnknownHostExc ...
- java在线截图---通过指定的URL对网站截图
如何以java实现网页截图技术 http://wenku.baidu.com/view/a7a8b6d076eeaeaad1f3305d.html http://blog.csdn.net/cping ...
- Java中获取完整的访问url
Java中获得完整的URl字符串: HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = &q ...
随机推荐
- webstorm快捷方式
刚开始在使用webstrom的时候,不知道快捷方式,感觉自己把webstorm当做记事本使用,真的挺傻的,在朋友的指导下,原来webstorm有快捷方式 一.界面操作 快捷键 说明 ctrl+shif ...
- C# WinForm给Button按钮或其它控件添加快捷键响应
就在这介绍三种添加快捷键的方式. 第一种Alt + *(按钮快捷键) 在大家给button.label.menuStrip等控件设置Text属性时在名字后边加&键名就可以了,比如button1 ...
- html5/css3响应式布局介绍及设计流程
html5/css3响应式布局介绍 html5/css3响应式布局介绍及设计流程,利用css3的media query媒体查询功能.移动终端一般都是对css3支持比较好的高级浏览器不需要考虑响应式布局 ...
- 检查ftp备份数据完整性及短信告警的shell脚本
发布:thebaby 来源:net [大 中 小] 检查ftp备份数据完整性及短信告警的shell,有需要的朋友可以参考下. 该脚本实现如下的功能: 对远程备份到ftp服务器的数据完整性及 ...
- WPF 得一些问题汇总
1.CallMethodAction <TextBox Height="30" Name="txtUserName" Width="160&qu ...
- web2.0最全的国外API应用集合
web2.0最全的国外API应用集合 原文地址:http://www.buguat.com/post/98.html 2.0时代,越来越多的API被大家广泛应用,如果你还不了解API是何物,请看这里的 ...
- swift 语法 - 以及学习资料
附上一些swift的一下学习资料: 1.Swift语法介绍官方英文版:The Swift Programming Language 2.Swift与Objective-C相互调用Using Swift ...
- shell脚本学习积累笔记(第一篇)
(1)首先,今天在执行shell脚本./test.sh时抛出“/bin/sh^M: bad interpreter: No such file or directory”的异常,百度后,才知道这是由于 ...
- Wild Words
poj1816:http://poj.org/problem?id=1816 题意:给你n个模板串,然后每个串除了字母,还有?或者*,?可以代替任何非空单个字符,*可以替代任何长度任何串,包括空字符串 ...
- Android学习及如何利用android来赚钱
一.如何学习Android android开发(这里不提platform和底层驱动)你需要对Java有个良好的基础,一般我们用Eclipse作为开发工具.对于过多的具体知识详细介绍我这里不展 ...