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 ...
随机推荐
- dom例子
//凡是html标签中的属性和值是一样的,那么在js中用true或者false 1,阅读协议倒计时 <input type="button" name="name& ...
- js 验证输入框金额
$("#ipt1").keyup(function () { var reg = $(this).val().match(/\d+\.?\d{0,2}/); var txt = ' ...
- html5音频和视频相关属性和方法
方法 方法 描述 addTextTrack() 为音视频加入一个新的文本轨迹 canPlayType() 检查指定的音视频格式是否得到支持 load() 重新加载音视频标签 play() 播放音视频 ...
- Python 命令行参数解析
方法1: Python有一个类可以专门处理命令行参数,先看代码: #!/usr/bin/env python # encoding: utf-8 from optparse import Option ...
- CGDataCmd
1,"Get Inf Joint from file" 选择文件中储存的骨骼信息; 2,"Export skinWeight" 导出权重; 3," ...
- leetcode第四题:Median of Two Sorted Arrays (java)
Median of Two Sorted Arrays There are two sorted arrays A and B of size m and n respectively. Find t ...
- 被windows“折磨”了一个礼拜
说是被windows折磨了一个礼拜,这话一点都不假!由于想彻底的卸载SQL Server而误删系统文件,导致系统重启之后持续蓝屏.无奈之下只能重装系统(心想,加入当初自己将系统备份的话,那该是多美好的 ...
- 【转】Spring 注解学习手札(超好的springmvc注解教程)
Spring 注解学习手札(一) 构建简单Web应用 Spring 注解学习手札(二) 控制层梳理 Spring 注解学习手札(三) 表单页面处理 Spring 注解学习手札(四) 持久层浅析 Spr ...
- 【转】来自GDXB大大大大的小总结
一 最短路 模型一 增加限制 例:给定一个图,求起点到终点的最短路,其中你可以使用最多k次机会使某条边的边权变为x. 解法:把每个点拆成k个点,分别表示还能使用多少次机会,构造新图. 模型二 一个点 ...
- 用js判断操作系统和浏览器类型
判断操作系统和浏览器的js代码 navigator.userAgent:userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值. navigator.pla ...