android端获取外网IP这个功能着实费了心思,试了不少方法,终于找到一个合适的。特意分享出来,希望能减少需要这个功能的程序猿们。
这是费尽心思找到的一个接口 ,忍痛分享出来:
//获取IP接口
public final static String GET_IP = "https://ifconfig.co/json";
//修正(2018-06-27):上边的ifconfig国内已经登录不上,查找后重新找到了可用的地址
public final static String GET_IP = "http://ip.chinaz.com/getip.aspx";
public final static String GET_IP = "http://www.3322.org/dyndns/getip";
获取IP值
//从接口中提取IP
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
try {
infoUrl = new URL(GlobalConfig.GET_IP);
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
JSONObject jsonObject = new JSONObject(strber.toString());
//从反馈的结果中提取出IP地址
return jsonObject.getString("ip");
}
} catch (Exception e) {
return "127.0.0.1";
}
return "127.0.0.1";
}
功能简单,但是。。。。分享值得点赞不是?!