java实现根据ip地址获取地理位置的代码分享
前几天想给网站后台加个解析ip所在地理位置的功能,在网上看了一些博客,找了几段程序,但总觉得写的不够简洁,感觉很啰嗦。下面这个程序,感觉还算简洁,于是整理调试了一下,可以用,程序调用了“腾讯ip分享计划”提供的接口,当然也可以改成ip138提供的接口,不过这两个网站返回的字符串格式有些不同,要分别做解析。
publicStringgetAddressByIP()
{
try
{
StringstrIP="0.0.0.0";
URLurl=newURL("http://ip.qq.com/cgi-bin/searchip?searchip1="+strIP);
URLConnectionconn=url.openConnection();
BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream(),"GBK"));
Stringline=null;
StringBufferresult=newStringBuffer();
while((line=reader.readLine())!=null)
{
result.append(line);
}
reader.close();
strIP=result.substring(result.indexOf("该IP所在地为:"));
strIP=strIP.substring(strIP.indexOf(":")+1);
Stringprovince=strIP.substring(6,strIP.indexOf("省"));
Stringcity=strIP.substring(strIP.indexOf("省")+1,strIP.indexOf("市"));
......
......
}
catch(IOExceptione)
{
return"读取失败";
}
}
附:
新浪接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
淘宝接口:http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短