用淘寶接口:(源碼:java 根據IP地址獲取地理位置)
pom.xml:
<!-- https://mvnrepository.com/artifact/net.sourceforge.jregex/jregex --> <dependency> <groupId>net.sourceforge.jregex</groupId> <artifactId>jregex</artifactId> <version>1.2_01</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
AddressUtils.java:
package com.euphe.util; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class AddressUtils { /** * * @param content * 請求的參數 格式為:name=xxx&pwd=xxx * @param encodingString * 服務器端請求編碼。如GBK,UTF-8等 * @return * @throws UnsupportedEncodingException */ public static String getAddresses(String content, String encodingString){ //調用淘寶API String urlStr = "http://ip.taobao.com/service/getIpInfo.php"; String returnStr = getResult(urlStr, content,encodingString); if(returnStr != null){
System.out.println(returnStr); return returnStr; } return null; } /** * @param urlStr * 請求的地址 * @param content * 請求的參數 格式為:name=xxx&pwd=xxx * @param encodingString * 服務器端請求編碼。如GBK,UTF-8等 * @return */ private static String getResult(String urlStr, String content, String encodingString) { URL url = null; HttpURLConnection connection = null; try { url = new URL(urlStr); // 新建連接實例 connection = (HttpURLConnection) url.openConnection(); // 設置連接超時時間,單位毫秒 //connection.setConnectTimeout(20000); // 設置讀取數據超時時間,單位毫秒 //connection.setReadTimeout(20000); //是否打開輸出流 connection.setDoOutput(true); //是否打開輸入流 connection.setDoInput(true); //提交方法 POST|GET connection.setRequestMethod("POST"); //是否緩存 connection.setUseCaches(false); //打開連接端口 connection.connect(); //打開輸出流往對端服務器寫數據 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //寫數據,即提交表單 name=xxx&pwd=xxx out.writeBytes(content); //刷新 out.flush(); //關閉輸出流 out.close(); // 往對端寫完數據對端服務器返回數據 ,以BufferedReader流來讀取 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encodingString)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null){ buffer.append(line); } reader.close(); return buffer.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(connection != null){ connection.disconnect(); } } return null; } }
測試:
@Test public void getAddressByIp() throws Exception { // 參數ip String ip = "219.136.134.157"; // json_result用於接收返回的json數據 String json_result = null; try { json_result = AddressUtils.getAddresses("ip=" + ip, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JSONObject json = JSONObject.fromObject(json_result); System.out.println("json數據: " + json); String country = JSONObject.fromObject(json.get("data")).get("country").toString(); String region = JSONObject.fromObject(json.get("data")).get("region").toString(); String city = JSONObject.fromObject(json.get("data")).get("city").toString(); String county = JSONObject.fromObject(json.get("data")).get("county").toString(); String isp = JSONObject.fromObject(json.get("data")).get("isp").toString(); String area = JSONObject.fromObject(json.get("data")).get("area").toString(); System.out.println("國家: " + country); System.out.println("地區: " + area); System.out.println("省份: " + region); System.out.println("城市: " + city); System.out.println("區/縣: " + county); System.out.println("互聯網服務提供商: " + isp); String address = country + "/"; address += region + "/"; address += city + "/"; address += county; System.out.println(address);
結果:
{"code":0,"data":{"country":"中國","country_id":"CN","area":"華南","area_id":"800000","region":"廣東省","region_id":"440000","city":"廣州市","city_id":"440100","county":"越秀區","county_id":"440104","isp":"電信","isp_id":"100017","ip":"219.136.134.157"}} 國家: 中國 地區: 華南 省份: 廣東省 城市: 廣州市 區/縣: 越秀區 互聯網服務提供商: 電信 中國/廣東省/廣州市/越秀區
但用淘寶的API時,真的很慢,少量數據還可以,一旦數據上萬,那就結束不了了,等了好久都運行不完。
沒辦法,開始嘗試其他方法。
用【GeoLite2 City】庫(源自:Java 通過Request請求獲取IP地址對應省份、城市)
pom.xml:
<dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.8.1</version> </dependency>
測試:
public static void main(String[] args) throws IOException{ // 創建 GeoLite2 數據庫 File database = new File("/Users/admin/GeoLite2-City.mmdb"); // 讀取數據庫內容 DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName("171.108.233.157"); // 獲取查詢結果 CityResponse response = null; try { response = reader.city(ipAddress); // 獲取國家信息 Country country = response.getCountry(); System.out.println(country.getIsoCode()); // 'CN' System.out.println(country.getName()); // 'China' System.out.println(country.getNames().get("zh-CN")); // '中國' // 獲取省份 Subdivision subdivision = response.getMostSpecificSubdivision(); System.out.println(subdivision.getName()); // 'Guangxi Zhuangzu Zizhiqu' System.out.println(subdivision.getIsoCode()); // '45' System.out.println(subdivision.getNames().get("zh-CN")); // '廣西壯族自治區' // 獲取城市 City city = response.getCity(); System.out.println(city.getName()); // 'Nanning' Postal postal = response.getPostal(); System.out.println(postal.getCode()); // 'null' System.out.println(city.getNames().get("zh-CN")); // '南寧' Location location = response.getLocation(); System.out.println(location.getLatitude()); // 22.8167 System.out.println(location.getLongitude()); // 108.3167 } catch (GeoIp2Exception e) { e.printStackTrace(); } }
這個就很快了,不過只能獲取到城市。