简体   繁体   中英

java.net.UnknownHostException:www.google.com

I am developing a sanity check web application. I tried getting url response using HttpUrlConnection method but I am getting UnknownHostException.

 System.setProperty("java.net.preferIPv4Stack" , "true");
    String[] uat_targetUrls={"https://www.google.com"};
    String[] uat_targetResponse=new String[uat_targetUrls.length];

            HttpURLConnection httpUrlConn;
            httpUrlConn = (HttpURLConnection) new URL(uat_targetUrls[i])
            .openConnection();

            httpUrlConn.setRequestMethod("GET");


            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);



           if(httpUrlConn.getResponseCode()==200)
               uat_targetResponse[i]="UP";
           else 
               uat_targetResponse[i]="DOWN";

When executing this, I am getting UnknownHostException for various urls. Can anyone help me on this. I am using Eclipse IDE. This is the error I am getting:

java.net.UnknownHostException: www.google.com
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)

Thanks.

The problem must be a networking issue on your machine.

Your code works for me (with some minor fixes to repair the missing loop variable i ):

public static void main(String[] args) throws Exception {
    System.setProperty("java.net.preferIPv4Stack", "true");
    String[] uat_targetUrls = { "https://www.google.com" };
    String[] uat_targetResponse = new String[uat_targetUrls.length];

    HttpURLConnection httpUrlConn;
    httpUrlConn = (HttpURLConnection) new URL(uat_targetUrls[0])
            .openConnection();

    httpUrlConn.setRequestMethod("GET");

    httpUrlConn.setConnectTimeout(30000);
    httpUrlConn.setReadTimeout(30000);

    if (httpUrlConn.getResponseCode() == 200)
        uat_targetResponse[0] = "UP";
    else
        uat_targetResponse[0] = "DOWN";


    System.out.println(uat_targetResponse[0]);
}

Output: UP

I tested the code provided by you, It seems working fine. UnknownHostException is thrown when IP address is not resolved. If you are in some organization, check if the network allows you to connect to network through code, or if DNS settings are proper.

使用ping www.google.com -4查看是否可以通过ipv4访问google.com。

try pinging www.google.com using

ping www.google.com -t 

if you get a time out error
Reason 1: No internet connection
Reason 2: You are probably behind an proxy server.
Reason 3: Add credentials to header

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