欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

教你一个获取当前 IP 地址和所在城市的小窍门。

最编程 2024-07-06 20:48:36
...

最近在做项目的登录日志模块,需要把当前用户登录的ip地址与所处城市写入到数据库中,因此在这里我分享一下如何调用API接口

一,获取本机ip地址

注意:这里指的是公网的IP地址,而不是局域网的IP地址,之前因为我是在学校,所以获取的本机IP是经过校园再分配的地址,不是公网的IP地址,导致定位失败。所以我们需要用到IP查询接口,之前用的是:http://ip.chinaz.com这个网址的接口,现在好像不能用了,于是又换了一个IP查询接口:http://whois.pconline.com.cn/

我们用URL资源定位符进行资源的拉取,然后利用正则表达式匹配我们想要的内容,这样便可以拿到我们本机的公网IP地址。

二,根据IP获取地理位置

当我们拿到本机的公网IP后,就可以使用接口来查询对应IP的地理位置了。我调用的是百度的ip定位api服务,详情参见:
http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm

测试代码

package com.oa.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class getLocationANDIp {


    private static String readAll(BufferedReader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }


    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    public Map<String,Object> getAddress() {
        String ip = "";
        // 这个网址似乎不能了用了
        // String chinaz = "http://ip.chinaz.com";
        // 改用了太平洋的一个网址
        String chinaz = "http://whois.pconline.com.cn/";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;

        Map<String,Object> map = new HashMap<>();
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            // 如有乱码的,请修改相应的编码集,这里是 gbk
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "gbk"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            // System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 这个是之前的正则表达式,
        // Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        // 通过正则表达式匹配我们想要的内容,根据拉取的网页内容不同,正则表达式作相应的改变
        Pattern p = Pattern.compile("显示IP地址为(.*?)的位置信息");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(0);
            // 这里根据具体情况,来截取想要的内容
            ip = ipstr.substring(ipstr.indexOf("为") + 2, ipstr.indexOf("的") - 1);
            System.out.println(ip);
            map.put("ip",ip);
        }
        JSONObject json = null;
        try {
            // 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
            json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=百度密钥&ip=" + ip);
            System.out.println(json);
            //city = (((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city")).toString();
            map.put("address",((JSONObject) json.get("content")).get("address").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args){
        getLocationANDIp getLocationANDIp = new getLocationANDIp();
        Map<String,Object> map =getLocationANDIp.getAddress();
        System.out.println(map.get("ip"));
        System.out.println(map.get("address"));
    }
}

上面这个类只需要导入一个json的jar包就可以,在maven项目的pom.xml文件中添加如下依赖:

   <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
  </dependency>

运行效果:


结果

推荐阅读