Nikhilesh Tiwari
Nikhilesh Tiwari

Reputation: 19

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.

Upvotes: 2

Views: 14729

Answers (4)

NevetsKuro
NevetsKuro

Reputation: 986

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

Upvotes: 1

yanyu
yanyu

Reputation: 227

Use ping www.google.com -4 to see if you can visit google.com by ipv4.

Upvotes: 0

Mohit Kanwar
Mohit Kanwar

Reputation: 3050

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.

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69329

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

Upvotes: 2

Related Questions