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. jquery ajax 的data 存表单的值

    jsp <body> <form action="" method="post" id="formid">  < ...

  2. jquery 之事件 多库共存(noConflict)

    /*jquery 之 简单事件jquery 与其它库共存,提供了 .noConflict() 方法,用法如下<script src="jquery 库"><scr ...

  3. DIV+CSS 网页布局之:三列布局

    1.宽度自适应三列布局 三列布局的原理和两列布局的原理是一样的,只不过多了一列,只需给宽度自适应两列布局中间再加一列,然后重新计算三列的宽度,就实现了宽度自适应的三列布局. 同样的道理,更多列的布局, ...

  4. mongodb3.2系统性学习——5、游标 模糊查询 findAndModify函数

    1首先介绍查询结果 返回的过程: 进行查询的时候mongodb 并不是一次哪个返回结果集合的所有文档,而是以多条文档的形式分批返回查询的结果,返回文档到内存中. 好处: 减少了客户端与服务器端的查询负 ...

  5. python【第十七篇】jQuery

    1.jQuery是什么? jQuery是一个 JavaScript/Dom/Bom 库. jQuery 极大地简化了 JavaScript 编程. jQuery 很容易学习. 2.jQuery对象与D ...

  6. 如何快速正确的安装 Ruby, Rails 运行环境-b

    对于新入门的开发者,如何安装 Ruby, Ruby Gems 和 Rails 的运行环境可能会是个问题,本页主要介绍如何用一条靠谱的路子快速安装 Ruby 开发环境.次安装方法同样适用于产品环境! 系 ...

  7. 关于BootStrap下图标的显示问题

    我现在在做自己的毕业设计,用到了bootstrap的这一套css样式,说句心里话,这一套东西确实很好用,但是一个小问题足足浪费了我将近两个小时. 我的问题是:没有办法使用bootstrap下的图标(很 ...

  8. 李洪强iOS开发之-环信02.3_具体接口讲解 - Apple Docs

    http://www.easemob.com/apidoc/ios/chat3.0/annotated.html Apple Docs.

  9. [wikioi]没有上司的舞会

    树形DP.用F[k][0]和F[k][1]表示某节点不选和选了之后子树的最大值.那么:f[i][0]=sigma(max(f[k][0],f[k][1]))f[i][1]=sigma(f[k][0]) ...

  10. [topcoder]TopographicalImage

    BFS.这里用了queue,以及在数据结构里存了上一个的高度.也可以递归调用完成BFS,在调用之前做判断:http://community.topcoder.com/stat?c=problem_so ...