大致思路是客户端发起请求,我们首先根据请求获取到外网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文件,大家可以百度一下,我在这里整理了一份放在网盘上了,有需要的可以下载一下

下载地址:

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();
    }

根据城市获取天气信息

第三方天气接口:portalweather.comsys.net.cn/weather03/a…

调用第三方天气接口获取天气信息,本文使用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);
}

总结

到此这篇关于java如何根据ip获取当前区域天气信息的文章就介绍到这了,更多相关java获取当前区域天气信息内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!