在java中检查url是否存在而不打开浏览器

时间:2011-06-15 08:57:53

标签: java

我想检查一个url的存在,并尝试在java中使用以下代码,

public boolean exists(String URLName) {
    try {
         if (!URLName.toUpperCase().contains("HTTP")) 
             URLName="http://"+URLName;
             URL url = new URL(URLName);
             System.setProperty("java.net.useSystemProxies", "true");
             HttpURLConnection urlConn = (HttpURLConnection)  url.openConnection();
                 urlConn.setConnectTimeout(9000);
         urlConn.setReadTimeout(9000);            
          urlConn.connect();                    
                         if(HttpURLConnection.HTTP_OK == urlConn.getResponseCode())
             return true;
else
             return false;
  }
 catch (SocketTimeoutException e){
        return false;
   }

 catch (Exception e) {
       e.printStackTrace();
       return false;
   }
}

上面的代码在windows中正常工作但是当代码通过服务器(linux)运行时,我收到以下错误消息,

GConf Error: Failed to contact configuration server; some possible
causes are that you need to enable TCP/IP networking for ORBit, or
you have stale NFS locks due to a system crash. See
http://projects.gnome.org/gconf/ for information. (Details - 1:
Not running within active session)
GConf Error: Failed to contact configuration server; some possible
causes are that you need to enable TCP/IP networking for ORBit, or
you have stale NFS locks due to a system crash. See
http://projects.gnome.org/gconf/ for information. (Details - 1:
Not running within active session)
java.net.UnknownHostException: www.ep.gov
at
java.net.PlainSocketImpl.connect(PlainSocketImpl.j ava:177)
at
java.net.SocksSocketImpl.connect(SocksSocketImpl.j ava:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java :158)
at
sun.net.http://www.http.HttpClient.openServe...lient.java:394)
at
sun.net.http://www.http.HttpClient.openServe...lient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java :233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:860)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:801)
at
sun.net.http://www.protocol.http.HttpURLConn...ction.java:726)

我从服务器管理员那里收到以下消息

It is working, while it was run in X session (GUI Mode).
But it is not working in non-GUI mode. Please try to change the coding to make use of non-GUI mode." It seems the above code is making use of GUI mode. 

我需要一个替代代码来检查网址是否存在而不使用GUI。

此致 琳达

2 个答案:

答案 0 :(得分:2)

UnknownHostException表示请求未到达目的地。可能有很多原因导致Linux服务器无法访问所需的URL www.ep.gov

请确保服务器可以访问网址www.ep.gov

答案 1 :(得分:1)

我认为你的问题出在这一行:

System.setProperty("java.net.useSystemProxies", "true");

这似乎导致系统尝试找到Web浏览器的HTTP代理配置,并最终遇到Gnome配置的一些问题。

您确实需要使用HTTP代理吗?如果没有,只需删除该行。如果您这样做,请阅读this page to learn how to configure proxies