java.net.UnknownHostException:www.google.com

余生长醉 提交于 2019-12-25 02:46:57

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/23825442/java-net-unknownhostexceptionwww-google-com

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!