以下是我尝试连接到不同 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)
我不确定这里缺少什么,我已连接到 Internet,并且正在我的 Eclipse Juno IDE 中运行此代码。