Use Taobao interface: (source code: java to obtain geographic location based on IP address )
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 * The parameter format of the request is: name=xxx&pwd=xxx * @param encodingString * Server-side request encoding. Such as GBK, UTF-8, etc. * @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 * the requested address * @param content * The parameter format of the request is: name=xxx&pwd=xxx * @param encodingString * Server-side request encoding. Such as GBK, UTF-8, etc. * @return */ private static String getResult(String urlStr, String content, String encodingString) { URL url = null; HttpURLConnection connection = null; try { url = new URL(urlStr); // Create a new connection instance connection = (HttpURLConnection) url.openConnection(); // Set the connection timeout, in milliseconds // connection.setConnectTimeout(20000); // Set the read data timeout , in milliseconds // connection.setReadTimeout(20000); // Whether to open the output stream connection.setDoOutput( true ); // Whether to open the input stream connection.setDoInput( true ); // Submit method POST|GET connection.setRequestMethod("POST" ); // Whether to cache connection.setUseCaches( false ); // Open the connection port connection.connect(); // Open the output stream to write data to the peer server DataOutputStream out = new DataOutputStream(connection. getOutputStream()); // Write data, that is, submit the form name=xxx&pwd=xxx out.writeBytes(content); // Refresh out.flush(); // Close the output stream out.close(); // To the peer After writing the data, the peer server returns the data and reads it with the BufferedReader stream 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:
@Test public void getAddressByIp() throws Exception { // parameter ip String ip = "219.136.134.157" ; // json_result is used to receive the returned json data 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( "Internet Service Provider: " + isp); String address = country + "/"; address += region + "/"; address += city + "/"; address += county; System.out.println(address);
result:
{"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"}} Country: China Region: South China Province: Guangdong Province City: Guangzhou District / County: Yuexiu District Internet Service Provider: Telecom China /Guangdong Province/Guangzhou City/Yuexiu District
However, when using Taobao's API, it is really slow, and a small amount of data is ok. Once the data exceeds 10,000, it will not end, and it will not end after waiting for a long time.
No way, start trying other methods.
Use the [GeoLite2 City] library (source: Java obtains the IP address corresponding to the province and city through the Request request )
pom.xml:
<dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.8.1</version> </dependency>
test:
public static void main(String[] args) throws IOException{ // Create GeoLite2 database File database = new File("/Users/admin/GeoLite2-City.mmdb" ); // Read database content DatabaseReader reader = new DatabaseReader. Builder(database).build(); InetAddress ipAddress = InetAddress.getByName("171.108.233.157"); // Get the query result CityResponse response = null ; try { response = reader.city(ipAddress); // Get country information Country country = response.getCountry(); System.out.println(country.getIsoCode()); // 'CN' System.out.println(country.getName()); // 'China' System.out.println(country.getNames().get("zh-CN")); // '中国' // Get province 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")); // 'Guangxi Zhuang Autonomous Region' // Get the city 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 (); } }
This is very fast, but can only get the city.