检查网址是否正常?

时间:2010-10-26 14:56:51

标签: java url

我需要检查特定网址是否已启动。 网址的格式类似于

http://IP:port

当我使用java.net.URL课程时,我会获得java.net.SocketExceptionjava.net.ConnectException

当我ping这些IP时,我发现它们为什么java无法识别它们?

我写的代码是

URL url = new URL( urlString );
HttpURLConnection httpConn =  (HttpURLConnection)url.openConnection();
httpConn.setInstanceFollowRedirects( false );
httpConn.setRequestMethod( "HEAD" ); 
httpConn.connect();

端口号必须使用! 如何使用java检查它们?

3 个答案:

答案 0 :(得分:1)

从这里工作得很好:

URL url = new URL( "http://google.com/" );
HttpURLConnection httpConn =  (HttpURLConnection)url.openConnection();
httpConn.setInstanceFollowRedirects( false );
httpConn.setRequestMethod( "HEAD" ); 
httpConn.connect();

System.out.println( "google.com : " + httpConn.getResponseCode());

或失败:

URL url = new URL( "http://google.com:666/" );
HttpURLConnection httpConn =  (HttpURLConnection)url.openConnection();
httpConn.setInstanceFollowRedirects( false );
httpConn.setRequestMethod( "HEAD" ); 
try{
    httpConn.connect();
     System.out.println( "google.com : " + httpConn.getResponseCode());
}catch(java.net.ConnectException e){
     System.out.println( "google.com:666 is down ");
}

答案 1 :(得分:1)

可能是服务器已启动并正在运行(响应ping),但没有HTTP服务器正在侦听该端口。

答案 2 :(得分:0)

也许还有其他事情发生但我发现这个页面让它完全符合您的要求: http://www.rgagnon.com/javadetails/java-0059.html

虽然它们在网址中没有端口号。