参考了一些博客,发现大部分都是通过访问外网再进行获取外网ip,本文是通过访问chinaz的接口返回的ip信息直接获取,有更好的办法可以指教一下,感谢!
package com.platform.api;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import sun.net.www.protocol.http.HttpURLConnection;
/**
* @author ajiu
*/
public class IpUtils {
public static String getIP() {
// String ip = "http://ip.chinaz.com/getip.aspx";
String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
String inputLine = "";
String read = "";
try {
URL url = new URL(ip);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((read = in.readLine()) != null) {
inputLine += read;
}
} catch (Exception e) {
e.printStackTrace();
}
return inputLine;
}
public static void main(String[] args) {
System.out.println(getIP());
}
}
2019/4/23
搜狐接口 http://pv.sohu.com/cityjson?ie=utf-8(默认GBK,可指定编码)
发现之前的接口已被限制,特在此修改