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. js判断是否全是相同的字符串

    isSameStr("aa2a") //不都是相同的字符 function isSameStr(str){ var tem=0; for(var i=0;i<str.leng ...

  2. c#代码自动修改解决方案下任意文件

    命名空间 using EnvDTE;using EnvDTE80; private DTE2 _applicationObject; public void AutoAddControl(插件 v_f ...

  3. SQLServer:定时作业

    SQLServer:定时作业: 如果在SQL Server 里需要定时或者每隔一段时间执行某个存储过程或3200字符以内的SQL语句时,可以用管理-SQL Server代理-作业来实现 也快可以定时备 ...

  4. Homebrew安装php5及composer for mac教程

    安装brew 可以查看教程:mac os x 10.9.1 安装 Homebrew软件包管理工具及brew安装maven3.1.1 首先更新下brew软件库 brew update brew tap ...

  5. Tasklist 命令的使用

    1,根据PID查找进程 tasklist /fi "pid eq 2245" 2,根据名称查找进程 tasklist /fi "imagename eq notepad. ...

  6. DSP:CCS V6 TMS320F2812 使用printf函数

    使用Code Composer Studio  Version: 6.1.1.00022,建立TMS320F2812工程. /* * main.c */ #include <stdio.h> ...

  7. lua之mysql编程

    环境搭建 #mysql 安装 sudo apt-get install mysql-server mysql-client # lua mysql 开发驱动安装 sudo apt-get instal ...

  8. 限制sqlserver最大内存后无法连接-EXEC sp_configure max server memory

    在sql server 中设置了过小的 "max server memory"最大内存后,sqlserver可启动,但是无法连接. 网络上流行的"sqlserver 内存 ...

  9. windows远程桌面连接配置

    我的电脑 -> 属性 -> 远程 把两个checkbox勾上 运行(win + r) -> 输入secpol.msc回车 -> 找到本地策略 -> 安全选项 ->账 ...

  10. 【网络流24题】 No.5 圆桌问题 (多重匹配)

    [题意] 假设有来自 n 个不同单位的代表参加一次国 际会议.每个单位的代表数分别为r i ni , = 1,2, .会议餐厅共有 m 张餐桌,每张餐桌可容纳 ci (i = 1,2, , m) 个 ...