1.前言
本來呢,想實現js定位功能,最少定位到城市,一開始,使用的是搜狐的api直接獲取數據,可是,有時候搜狐不可靠,只能得到
公網ip,其他信息無用,就像這樣
2.既然這樣,還不如我自己請求自己的服務器,讓服務器獲取該請求的公網ip,然后再根據公網ip獲取信息,
服務器解析請求公網IP的源碼:
1 public String getIpAddr(HttpServletRequestrequest) { 2 String ip = request.getHeader("x-forwarded-for"); 3 if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) { 4 ip = request.getHeader("Proxy-Client-IP"); 5 } 6 if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) { 7 ip = request.getHeader("WL-Proxy-Client-IP"); 8 } 9 if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) { 10 ip = request.getRemoteAddr(); 11 } 12 return ip; 13 }
但是,這樣會對開發的過程造成麻煩,因為在機上開啟服務,然后在本機網頁訪問測試,返回的ip地址是127.0.0.1,而同在一個局域網的機器訪問的時候返回的ip是這台機器的ip地址192.168.xxx,只有當外網的客戶端訪問的時候,返回的ip是才是外網客戶端的公網ip地址。
因此,獲取公網IP的方法仍采用搜狐的api,然后再請求服務器,服務器去請求淘寶的ip接口獲取ip信息,
為啥用淘寶的?因為免費呀,速度也快,ip庫數據多。
3.搜狐api調用方式
1 <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> 2 <%-- var returnCitySN = {"cip": "223.73.101.129", "cid": "CN", "cname": "CHINA"};--%> 3 <script> 4 //獲取公網ip 5 document.write(returnCitySN["cip"]); 6 console.log(returnCitySN); 7 </script>
直接使用結果就可以
4.java調用淘寶api接口,獲取公網ip信息
源碼:

1 import org.junit.Test; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.URL; 9 import java.util.Map; 10 11 public class GetLocationByIP { 12 13 @Test 14 public void IpUtils(){ 15 String s = ipToCountry("223.73.41.129"); 16 System.out.println(s); 17 } 18 19 20 //通過公網ip獲取地理信息 21 public static String ipToCountry(String ip){ 22 String website="http://ip.taobao.com/service/getIpInfo.php?ip="+ip; 23 String read=""; 24 URL url=null; 25 HttpURLConnection urlConnection=null; 26 BufferedReader in=null; 27 try { 28 url=new URL(website); 29 urlConnection=(HttpURLConnection)url.openConnection(); 30 in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8")); 31 read=in.readLine(); 32 } catch (MalformedURLException e) { 33 e.printStackTrace(); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 }finally{ 37 if (in!=null){ 38 try { 39 in.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 } 45 return read; 46 // Map readMap = FastJson.getJson().parse(read, Map.class); 47 // Map data = FastJson.getJson().parse(readMap.get("data").toString(), Map.class); 48 // return data.get("country").toString(); 49 } 50 51 52 53 }
測試截圖:
淘寶api接口有缺點,頻繁請求會出現502異常:
這就讓我很不爽了,可以使用其他公司的api代替,不僅僅淘寶一家有ip數據庫
也可以使用太平洋網的接口,花樣更多了,根據自己需要使用
api網址 : http://whois.pconline.com.cn/
參考博客原址: https://cloud.tencent.com/developer/article/1152362