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 ...
随机推荐
- Windows平台下Qt开发环境的搭建
Qt 是采用开源和商用双协议发布的开放源代码的图形开发类库,现在很多图形化的开源软件都使用了Qt. 下载地址:http://qt-project.org/downloads 1. 下载安装包 你可以从 ...
- demo_07选择器练习
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- mac下Apache + MySql + PHP网站开发
最近接了个小活,做一个使用PHP语言和MySql数据库的动态网站.之前做过类型的网站,是在windows系统下做的,开发环境使用的是 AppServ 的PHP开发套件.现在有了我的大MAC,所以找了M ...
- Mysql 与 php动态网站开发 入门教程
这个系列的教程由表单开始写,因为表单可以把数据库和web 之间的交互表现得很明显.提交表单 ,数据库记录注册信息. 本教程属于基础教程.大神请略过. 对于php和mysql之间的稳固性很 ...
- LED汽车前大灯
一.LED汽车前大灯遇到问题.分析和解决 问题1: 当电源电压增大时,LED等闪烁,而且电源电压增大的越多闪烁的频率越低. 原因分析: 电源电压从12V升高到24V过程中,开关MOS管的Vds增大,Q ...
- 【网络流24题】No.16 数字梯形问题 (不相交路径 最大费用流)
[题意] 给定一个由 n 行数字组成的数字梯形如下图所示. 梯形的第一行有 m 个数字.从梯形的顶部的 m 个数字开始,在每个数字处可以沿左下或右下方向移动, 形成一条从梯形的顶至底的路径.规则 1: ...
- Java+JQuery实现网页显示本地文件目录(含源码)
原文地址:http://www.cnblogs.com/liaoyu/p/uudisk.html 源码地址:https://github.com/liaoyu/uudisk 前段时间为是练习JQuer ...
- PAIP.提升效率----论项目知识库的建设。。
PAIP.提升效率----论项目知识库的建设.. 作者Attilax , EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.net ...
- 【HDOJ】4585 Shaolin
Set可解,Treap也可解.(1) Treap /* */ #include <iostream> #include <string> #include <map> ...
- 全球AI界最值得关注的十位科学家
全球AI界最值得关注的十位科学家 我们可以看到AI已经从象牙塔里的高冷研究,逐步转换为科技公司.互联网公司的最核心竞争力.AI代表了这时代人类的前沿智慧,也正达到一种科学的极致. 这两天在美国加利 ...