java 根据ip获取地址

Posted Shaw_喆宇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 根据ip获取地址相关的知识,希望对你有一定的参考价值。

用淘宝接口:(源码: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();
        }     


}  

这个就很快了,不过只能获取到城市。


以上是关于java 根据ip获取地址的主要内容,如果未能解决你的问题,请参考以下文章

java根据ip地址获取相应的所在地,精确到街道和门牌号,要怎么实现?

java 根据ip获取地址

Java如何根据主机名(域名)获取IP地址?

根据ip地址获取用户所在地

在linux用java根据ip获得mac地址?

Java根据ip地址获取归属地