简体   繁体   中英

Testing URL with HttpUrlConnection only works with www in front

I am writing a program that tests different URLs. I am using HttpURLConnection and it works fine for most URLs except at least one of them requires having the url have "www." in the front while most don't.

Does anyone know why this is? I get a 200 response when I have a www. in front but I'd prefer to not have to append that if I don't need to since not all of my sites start with 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();
    }

Output: java.net.UnknownHostException: at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) 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) at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source) 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) at com.workfromhome.UrlChecker.main(UrlChecker.java:19)

I have run your code, your code runs fine. What your are experiencing is an issue with how the domain/DNS is registered for specific sites. In order to not have the www listed in front of the URL, it requires a second DNS registration, so is site specific.

See this link:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM