其他分享
首页 > 其他分享> > 根据IP地址获取地理位置

根据IP地址获取地理位置

作者:互联网

1)根据IP地址获取地理位置

获取本机的公网IP,使用接口来查询对应IP的地理位置。调用百度的ip定位api服务,详情参考:百度地图api

参考代码如下:

package com.example.addressip.utils;

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author relax
 * @version 1.0
 * @功能描述:根据ip获取地址
 * @date 2021/10/11 22:18
 */
public class AddressIpUtil {

    /**
     * 在使用正则表达式时,利用好其预编译功能,可以有效加快正则匹配速度。
     * 官方提醒:在使用正则表达式时,利用好其预编译功能,可以有效加快正则匹配速度。 说明:不要在方法体内定义。
     * 其实插件的意思是让我们把这个信息抽取到方法外面使其触发预编译。
     * 通过正则表达式匹配我们想要的内容,根据拉取的网页内容不同,正则表达式作相应的改变
     */
    private static final Pattern pattern = Pattern.compile("显示IP地址为(.*?)的位置信息");
    private static final String akCode = "A64YQ6I7s7HCqBmXoAQLYdbk2Vd****";

    /**
     * 读取所有内容
     *
     * @param rd
     * @return
     * @throws IOException
     */
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    /**
     * 拉取网页所有内容,并转化为Json格式
     *
     * @param url
     * @return
     * @throws IOException
     * @throws JSONException
     */
    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 String getAddress() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        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");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        Matcher m = pattern.matcher(inputLine.toString());
        if (m.find()) {
            String ipStr = m.group(0);
            // 这里根据具体情况,来截取想要的内容
            ip = ipStr.substring(ipStr.indexOf("为") + 2, ipStr.indexOf("的") - 1);
            System.out.println(ip);
        }
        JSONObject json = null;
        String city = 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=" + akCode + "&ip=" + ip);
            System.out.println(json);
            city = (((JSONObject) ((JSONObject) json.get("content"))
                    .get("address_detail")).get("city")).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return city;
    }

    public static void main(String[] args) {
        AddressIpUtil Addr = new AddressIpUtil();
        String addr = Addr.getAddress();
        System.out.println(addr);
    }
}

需要引入的依赖

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

本文来源于CSDN作者:jam_fanatic

标签:String,地理位置,ip,获取,json,IP地址,new,import,null
来源: https://www.cnblogs.com/lwx768561/p/15583714.html