java根据IP获取当前区域天气信息

该博客介绍了如何在Java中实现通过客户端IP获取外网IP,然后利用ip2region.db数据库确定用户所在城市,并进一步获取该城市的天气信息。主要涉及的技术包括HTTP请求、正则表达式、IP定位库ip2region以及第三方天气API的调用。
摘要由CSDN通过智能技术生成

大致思路是客户端发起请求,我们首先根据请求获取到外网IP,然后再根据外网IP获取到用户所在城市,最后根据城市获取到天气信息

获取外网IP

万网获取外网IP地址

/**
 * @Description:获取客户端外网ip 此方法要接入互联网才行,内网不行
 **/
public static String getPublicIp() {
    try {
        String path = "http://www.net.cn/static/customercare/yourip.asp";// 要获得html页面内容的地址(万网)

        URL url = new URL(path);// 创建url对象

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 打开连接

        conn.setRequestProperty("contentType", "GBK"); // 设置url中文参数编码

        conn.setConnectTimeout(5 * 1000);// 请求的时间

        conn.setRequestMethod("GET");// 请求方式

        InputStream inStream = conn.getInputStream();
        // readLesoSysXML(inStream);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                inStream, "GBK"));
        StringBuilder buffer = new StringBuilder();
        String line;
        // 读取获取到内容的最后一行,写入
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        List<String> ips = new ArrayList<>();

        //用正则表达式提取String字符串中的IP地址
        String regEx="((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)";
        String str = buffer.toString();
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find()) {
            String result = m.group();
            ips.add(result);
        }

        // 返回公网IP值
        return ips.get(0);

    } catch (Exception e) {
        System.out.println("获取公网IP连接超时");
        return "";
    }
}

根据外网IP获取用户所在城市

首先你待需要一个ip2region.db文件,大家可以百度一下,我在这里整理了一份放在网盘上了,有需要的可以下载一下

链接:https://pan.baidu.com/s/1cR5VSzWEXjL5olOOjJBL6g 提取码:asdn

这边是另一个账号上的ip2region.db的 下载地址:https://download.csdn.net/download/asn4513/20629211?spm=1001.2014.3001.5501

ip2region 准确率99.9%的ip地址定位库,0.0x毫秒级查询,数据库文件大小只有1.5M,提供了java,php,c,python,nodejs,golang查询绑定和Binary,B树,内存三种查询算法

引入ip2region.db

在这里插入图片描述
maven依赖

<!--ip2region-->
<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7.2</version>
</dependency>

创建IPUtils工具类

@Log4j2
public class IPUtils {

    /**
     * 根据IP获取地址
     *
     * @return 国家|区域|省份|城市|ISP
     */
    public static String getAddress(String ip) {
        return getAddress(ip, DbSearcher.BTREE_ALGORITHM);
    }

    /**
     * 根据IP获取地址
     *
     * @param ip
     * @param algorithm 查询算法
     * @return 国家|区域|省份|城市|ISP
     * @see DbSearcher
     * DbSearcher.BTREE_ALGORITHM; //B-tree
     * DbSearcher.BINARY_ALGORITHM //Binary
     * DbSearcher.MEMORY_ALGORITYM //Memory
     */
    @SneakyThrows
    public static String getAddress(String ip, int algorithm) {
        if (!Util.isIpAddress(ip)) {
            log.error("错误格式的ip地址: {}", ip);
            return "";
        }
        String dbPath = IPUtils.class.getResource("/db/ip2region.db").getPath();
        File file = new File(dbPath);
        if (!file.exists()) {
            log.error("地址库文件不存在");
            return "";
        }
        DbSearcher searcher = new DbSearcher(new DbConfig(), dbPath);
        DataBlock dataBlock;
        switch (algorithm) {
            case DbSearcher.BTREE_ALGORITHM:
                dataBlock = searcher.btreeSearch(ip);
                break;
            case DbSearcher.BINARY_ALGORITHM:
                dataBlock = searcher.binarySearch(ip);
                break;
            case DbSearcher.MEMORY_ALGORITYM:
                dataBlock = searcher.memorySearch(ip);
                break;
            default:
                log.error("未传入正确的查询算法");
                return "";
        }
        searcher.close();
        return dataBlock.getRegion();
    }

根据城市获取天气信息

第三方天气接口:http://portalweather.comsys.net.cn/weather03/api/weatherService/getDailyWeather?cityName=?

调用第三方天气接口获取天气信息,本文使用java自带工具类HttpUtils

@GetMapping("/weather")
@DecryptBody(encode = true) //响应加密
public Result getWeather(){
    String publicIp = GetIPUtils.getPublicIp();//获取外网IP
    if (StringUtils.isBlank(publicIp)) return ResultUtils.error("获取失败");
    String cityInfo = IPUtils.getAddress(publicIp);//国家|区域|省份|城市|ISP
    if (StringUtils.isBlank(cityInfo)) return ResultUtils.error("获取失败");
    String[] split = cityInfo.split("\|");
    String city = "";
    for (String aSplit : split) if (aSplit.contains("市")) city = aSplit;//拿取市级名称
    if (StringUtils.isBlank(city)) return ResultUtils.error("获取失败");
    String weatherInformation = HttpUtil.get("http://portalweather.comsys.net.cn/weather03/api/weatherService/getDailyWeather?cityName=" + city);//调用天气接口
    if (StringUtils.isBlank(weatherInformation)) return ResultUtils.error("获取失败");
    Object o = ObjectMapperUtils.strToObj(weatherInformation,Object.class);
    return ResultUtils.success("获取成功",o);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,要根据 IP 地址获取归属地,可以使用 Java 自带的 `InetAddress` 类和 `ip138` 等在线查询工具。 以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IPUtils { /** * 根据 IP 地址获取归属地 * * @param ip IP 地址 * @return 归属地字符串 * @throws IOException */ public static String getIpAddress(String ip) throws IOException { InetAddress inetAddress = InetAddress.getByName(ip); String hostAddress = inetAddress.getHostAddress(); String url = "http://www.ip138.com/ips138.asp?ip=" + hostAddress + "&action=2"; URLConnection connection = new URL(url).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); String content = stringBuilder.toString(); String regex = "<li>本站主数据:(.*?)</li>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); if (matcher.find()) { return matcher.group(1); } return "未知"; } public static void main(String[] args) throws IOException { String ip = "113.96.208.44"; String address = getIpAddress(ip); System.out.println(ip + " 的归属地是:" + address); } } ``` 该代码通过 `InetAddress` 类获取 IP 地址的主机名,然后构造查询 URL,请求 IP138 等在线查询工具获取归属地信息,并使用正则表达式从响应内容中提取出归属地。注意需要设置读取响应的字符编码为 GBK。 需要注意的是,该方法仅供学习和参考,实际应用中可能存在 IP 地址和归属地不匹配的情况,也可能存在在线查询工具挂掉或者响应超时的情况,需要根据实际情况进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值