使用HttpUrlConnection测试URL仅适用于前面的www

时间:2016-02-14 15:19:03

标签: java url web httpurlconnection ping

我正在编写一个测试不同网址的程序。我正在使用HttpURLConnection,它适用于大多数URL,除了其中至少有一个要求网址有" www。"在前面,而大多数人都没有。

有谁知道这是为什么?当我有一个www时,我收到200响应。在前面但我不想附加,如果我不需要,因为并非我的所有网站都以www开头。

    url = "http://" + url;

    System.out.println("Testing " + url);


    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = conn.getResponseCode();

        switch(responseCode){
        case 200: System.out.println("URL is valid."); 
                break;
        case 301: case 302: case 303: System.out.println("URL is being redirected."); 
            redirect(conn); 
            break;
        default: System.out.println("URL not valid."); 
        break;
        }


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

输出:     的java.net.UnknownHostException:     在java.net.AbstractPlainSocketImpl.connect(未知来源)     在java.net.PlainSocketImpl.connect(未知来源)     在java.net.SocksSocketImpl.connect(未知来源)     在java.net.Socket.connect(未知来源)     在java.net.Socket.connect(未知来源)     在sun.net.NetworkClient.doConnect(未知来源)     at sun.net.www.http.HttpClient.openServer(Unknown Source)     at sun.net.www.http.HttpClient.openServer(Unknown Source)     在sun.net.www.http.HttpClient。(未知来源)     在sun.net.www.http.HttpClient.New(未知来源)     在sun.net.www.http.HttpClient.New(未知来源)     at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)     at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)     at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)     在sun.net.www.protocol.http.HttpURLConnection.connect(未知来源)     at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)     at java.net.HttpURLConnection.getResponseCode(Unknown Source)     在com.workfromhome.UrlChecker.main(UrlChecker.java:19)

1 个答案:

答案 0 :(得分:0)

我运行了你的代码,你的代码运行正常。您遇到的问题是域名/ DNS如何为特定站点注册。为了不在URL前面列出www,它需要第二次DNS注册,因此是特定于站点的。

请看这个链接:

http://www.webdeveloper.com/forum/showthread.php?218551-Why-do-some-site-require-quot-www-quot-at-the-front-of-the-domain-and-some-don-t