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);
}
} }
  1. Is this any good at all (will it do what I want?)
  2. Do I have to somehow close the connection?
  3. 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的更多相关文章

  1. java.net.MalformedURLException: Illegal character in URL

    在进行接口测试时,意外发现返回结果报java.net.MalformedURLException: Illegal character in URL,意思是“在URL中的非法字符”,我的参数是经过ba ...

  2. URL中增加BASE64加密的字符串引起的问题(java.net.MalformedURLException:Illegal character in URL)

    序 昨天在做一个 Demo 的时候,因为是调用第三方的接口,採用的是 HTTP 的通信协议,依照文档上的说明,须要把參数进行加密后增加到 URL 中.可是,就是这个看似普普通通的操作,却让我着实费了非 ...

  3. 无法解析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 ...

  4. java匹配http或https的url的正则表达式20180912

    package org.jimmy.autosearch20180821.test; import java.util.regex.Matcher; import java.util.regex.Pa ...

  5. JAVA提取字符串中所有的URL链接,并加上a标签

    工具类 Patterns.java 1 package com.util; 2 3 import java.util.regex.Matcher; 4 import java.util.regex.P ...

  6. Java魔法堂:URI、URL(含URL Protocol Handler)和URN

    一.前言 过去一直搞不清什么是URI什么是URL,现在是时候好好弄清楚它们了!本文作为学习笔记,以便日后查询,若有纰漏请大家指正! 二.从URI说起    1. 概念 URI(Uniform Reso ...

  7. java基础:网络编程TCP,URL

    获取域名的两种方法: package com.lanqiao.java.test; import java.net.InetAddress;import java.net.UnknownHostExc ...

  8. java在线截图---通过指定的URL对网站截图

    如何以java实现网页截图技术 http://wenku.baidu.com/view/a7a8b6d076eeaeaad1f3305d.html http://blog.csdn.net/cping ...

  9. Java中获取完整的访问url

    Java中获得完整的URl字符串: HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = &q ...

随机推荐

  1. CSS3鼠标移入移出图片生成随机动画

    今天分享使用html+css3+少量jquery实现鼠标移入移出图片生成随机动画,我们先看最终效果图(截图为静态效果,做出来可是动态的哟) 左右旋转 上下移动 缩放 由于时间关系我就不一步步解析各段代 ...

  2. Avoiding “will create implicit index” NOTICE

    执行PgSql避免 notice 信息,执行之前加入以下语句调整报错级别即可: SET CLIENT_MIN_MESSAGES = ‘WARNING’;

  3. Vue.js 2.0 和 React、Augular

    Vue.js 2.0 和 React.Augular 引言 这个页面无疑是最难编写的,但也是非常重要的.或许你遇到了一些问题并且先前用其他的框架解决了.来这里的目的是看看Vue是否有更好的解决方案.那 ...

  4. 双积分式(A/D)转换器电路结构及工作原理

    1.转换方式 V-T型间接转换ADC. 2.  电路结构 图1是这种转换器的原理电路,它由积分器(由集成运放A组成).过零比较器(C).时钟脉冲控制门(G)和计数器(ff0-ffn)等几部分组成 图1 ...

  5. UIPageControll - 图片格式

    设置pageCon的显示风格: 1. 颜色 page.pageIndicatorTintColor = [UIColor redColor]; page.currentPageIndicatorTin ...

  6. 第十二周项目一 教师兼干部类】 共建虚基类person

    项目1 - 教师兼干部类]分别定义Teacher(教师)类和Cadre(干部)类,采用多重继承方式由这两个类派生出新类Teacher_Cadre(教师兼干部).要求: (1)在两个基类中都包含姓名.年 ...

  7. C++引用之引用的使用

    一旦一个引用被声明,则该引用名就只能作为目标变量名的一个别名来使用,所以,不能再把该引用名作为其他变量名的别名,任何对该引用的赋值就是对该引用对应的目标变量名的赋值. 对引用求地址就是对目标变量求地址 ...

  8. Apache httpd.conf的翻译

    本人初学,15年暑假翻译了一些,前几天翻译完,有机器翻译,也有自己翻译的内容,不准确之处请指出. --------------------------------------------------- ...

  9. [OI笔记] 最长上升子序列与网络流建模

    与最长上升子序列相关的网络流问题: 给定一个序列 A[1..n] ,求出 A 的最长上升子序列长度.并且回答下列询问: (1) 如果每个点只能用一次,能从 A 中取出几个最长上升子序列? (2) 如果 ...

  10. [转贴] C/C++中动态链接库的创建和调用

    DLL 有助于共享数据和资源.多个应用程序可同时访问内存中单个DLL 副本的内容.DLL 是一个包含可由多个程序同时使用的代码和数据的库.下面为你介绍C/C++中动态链接库的创建和调用. 动态连接库的 ...