前幾天想給網站後台加個解析ip所在地理位置的功能,在網上看了一些博客,找了幾段程序,但總覺得寫的不夠簡潔,感覺很啰嗦。下面這個程序,感覺還算簡潔,於是整理調試了一下,可以用,程序調用了“騰訊ip分享計劃”提供的接口,當然也可以改成ip138提供的接口,不過這兩個網站返回的字符串格式有些不同,要分別做解析。
public String getAddressByIP()
{
try
{
String strIP = "0.0.0.0";
URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
String line = null;
StringBuffer result = new StringBuffer();
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
strIP = result.substring(result.indexOf( "該IP所在地為:" ));
strIP = strIP.substring(strIP.indexOf( ":") + 1);
String province = strIP.substring(6, strIP.indexOf("省"));
String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));
... ...
... ...
}
catch( IOException e)
{
return "讀取失敗";
}
}
附:
新浪接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
淘寶接口:http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]