java實現(xiàn)根據(jù)ip地址獲取地理位置的代碼分享
前幾天想給網(wǎng)站后臺加個解析ip所在地理位置的功能,在網(wǎng)上看了一些博客,找了幾段程序,但總覺得寫的不夠簡潔,感覺很啰嗦。下面這個程序,感覺還算簡潔,于是整理調(diào)試了一下,可以用,程序調(diào)用了“騰訊ip分享計劃”提供的接口,當然也可以改成ip138提供的接口,不過這兩個網(wǎng)站返回的字符串格式有些不同,要分別做解析。
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地址字串]
相關(guān)文章
spring?boot集成smart-doc自動生成接口文檔詳解
這篇文章主要介紹了spring?boot集成smart-doc自動生成接口文檔詳解,smart-doc是一款同時支持java?restful?api和Apache?Dubbo?rpc接口文檔生成的工具,smart-doc顛覆了傳統(tǒng)類似swagger這種大量采用注解侵入來生成文檔的實現(xiàn)方法2022-09-09
java報錯Cause: java.sql.SQLException問題解決
本文主要介紹了java報錯Cause: java.sql.SQLException問題解決,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08
MybatisPlus?自定義插件實現(xiàn)攔截SQL修改功能(實例詳解)
這篇文章主要介紹了MybatisPlus?自定義插件實現(xiàn)攔截SQL修改功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11
Java實現(xiàn)讀取html文本內(nèi)容并按照格式導出到excel中
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)讀取html文本提取相應內(nèi)容按照格式導出到excel中,文中的示例代碼講解詳細,需要的可以參考下2024-02-02

