在项目中,我们有时需要获取外网的地址,这里指的地址是公网的ip地址,我们大多数机器实际上都是处于内网,要想查看我们的公网ip,我们可以登录一些网站,如www.ip138.com之类的网站,就可以显示我们的公网ip。这里提供一种解决方案,正是基于这种思想,从网站上抓取我们需要的内容。好了,看代码:
手机充值:http://yjck67.taobao.com,自己的小店
public static String getWanIp() {
String inputLine = "";
String read = "";
String ip = "";
try {
URL url = new URL("http://checkip.dyndns.org/");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
while ((read = in.readLine()) != null) {
inputLine += read;
}
String[] strs = inputLine.split(":");
ip = strs[1].split("<")[0];
} catch (Exception e) {
e.printStackTrace();
}
return ip.trim();
}
其思路就是打开能测试到外网ip的网站,然后解析其显示内容,拿到我们需要的东西。