连接到URL时获取连接超时以获取IP详细信息

时间:2013-09-23 15:16:19

标签: java geolocation ip

以下是我的代码,它尝试连接到不同的URL,提供有关IP地址的详细信息。

    public static void main(String args []) throws Exception, URISyntaxException {

    String ip = "2.51.255.200";
    // http://whois.net/ip-address-lookup/
    // http://www.geobytes.com/IpLocator.htm?GetLocation&IpAddress=162.115.44.104
    // http://whatismyipaddress.com/ip/162.115.44.104
    // http://freegeoip.net/csv/137.188.83.252
    URL url = new URL("http://whatismyipaddress.com/ip/162.115.44.104");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.3 Safari/537.31");
    connection.connect();

    InputStream is = connection.getInputStream();

    int status = connection.getResponseCode();
    if (status != 200) {
        return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    for (String line; (line = reader.readLine()) != null;) {
        //this API call will return something like:

       // "2.51.255.200","AE","United Arab Emirates","03","Dubai","Dubai","","x-coord","y-coord","",""
        // you can extract whatever you want from it
        System.out.println(line);
    }       
}

当我运行此代码时,它给出了连接超时异常,如下所示。

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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.<init>(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.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at com.vzw.velite.services.TestURL.main(TestURL.java:22)

我不确定这里缺少什么,我已连接到互联网,我在Eclipse Juno IDE中运行此代码。

0 个答案:

没有答案