Title

调用第三方Api获取天气信息

根据ip获取城市信息

  • 导包
<!--IP地址解析-->
<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7.2</version>
</dependency>
<!--json字符串解析-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.72</version>
</dependency>
  • 下载依赖库 ip2region.db

https://gitee.com/lionsoul/ip2region/tree/master/data

下载解压后只需要 data 目录下的 ip2region.db

ip2region.db 可以复制到 resources 目录下( maven 项目)

  • 获取城市信息
//获取ip所在地址
    public static String getAddressByIp(String ip) {
        try {
            //db
            URL url = ip2regionTest.class.getClassLoader().getResource("ip2region.db");
            String dbPath = url.getFile();
            File file = new File(url.getFile());
            if (file.exists() == false) {
                System.out.println("Error: Invalid ip2region.db file");
            }
 
            //查询算法
            int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
            //int algorithm = DbSearcher.BINARY_ALGORITHM; //Binary
            //int algorithm = DbSearcher.MEMORY_ALGORITYM; //Memory
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            //define the method
            Method method = null;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false) {
                System.out.println("Error: Invalid ip address");
            }
            dataBlock = (DataBlock) method.invoke(searcher, ip);
            //address格式:中国|0|广东省|深圳市|电信
            String address = dataBlock.getRegion();
            //下两行 防止截取报错 在本方法catch
            String[] splitIpString = address.split("\\|");
            String succ = splitIpString[4];
            return address;
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

// 测试
public static void main(String[] args) {
        String addressByIp = getAddressByIp("14.215.177.38");
        System.out.println(addressByIp);
}

效果

根据城市信息获取天气信息

免费的Api接口

国国家气象局

http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html

注意:

上面url中的“101010100”是城市代码,这里指代“北京”的城市代码。只需要改变城市代码,就可以得到所在城市的天气信息。

万年历 (支持未来几天预告)

http://wthrcdn.etouch.cn/weather_mini?city=北京
http://www.sojson.com/open/api/weather/json.shtml?city=北京

第二个Api接口变化请到 http://www.sojson.com/api/weather.html 查看详情

  • 使用

天气实体类

public class WeatherInfo {
    private String date;        //时间
    private String week;        //星期
    private String lunar;       //农历时间
    private String cityname;    //城市名
    private String weather;     //天气
    private String temp;        //当前温度
    private String highTemp;    //最高温度
    private String lowTemp;     //最低温度
    private String tips;        //小提示
 
    ... (省略get,set,toString方法)
 
}
  • 天气获取工具类
package com.cqdpark.modules.generator.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqdpark.modules.generator.vo.WeatherInfoVO;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.zip.GZIPInputStream;

/**
 * 天气工具类
 *
 * @author z
 */
public class WeatherUtils {
    private static String weatherUrl = "http://wthrcdn.etouch.cn/weather_mini?city=";
    private static String cityUrl = "http://ip.ws.126.net/ipquery?ip=";
    /**
     * 通过城市名称获取该城市的天气信息
     */
    public static String GetWeatherData(String cityname) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            URL url = new URL(weatherUrl + cityname);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            GZIPInputStream gzin = new GZIPInputStream(is);
            // 设置读取流的编码格式,自定义编码
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            reader = new BufferedReader(isr);
            String line = null;
            while((line = reader.readLine()) != null){
                sb.append(line + " ");
            }
            reader.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 将JSON格式数据进行解析 ,返回一个weather对象
     */
    public static WeatherInfoVO GetWeather(String weatherInfobyJson){
        JSONObject dataOfJson = JSONObject.parseObject(weatherInfobyJson);   // json天气数据
        if(dataOfJson.getIntValue("status") != 1000){
            return null;
        }
        // 创建WeatherInfo对象,提取所需的天气信息
        WeatherInfoVO weatherInfo = new WeatherInfoVO();

        // 获取当前日期:日期、星期
        Calendar cal = Calendar.getInstance();    							     // Calendar类的实例化
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");  // 时间的格式化
        weatherInfo.setDate(sdf1.format(cal.getTime()));                // 时间
        SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE");
        weatherInfo.setWeek(sdf2.format(cal.getTime()));                // 星期

        // 从json数据中提取数据:城市、温度、小提醒
        dataOfJson = JSONObject.parseObject(dataOfJson.getString("data"));
        weatherInfo.setCityname(dataOfJson.getString("city"));            // 城市
        weatherInfo.setTemp(dataOfJson.getString("wendu"));               // 温度
        weatherInfo.setTips(dataOfJson.getString("ganmao"));              // 小提示

        // 获取今天的天气预报信息:最高温度、最低温度、天气
        JSONArray forecast = dataOfJson.getJSONArray("forecast");
        JSONObject result = forecast.getJSONObject(0);
        weatherInfo.setHighTemp(result.getString("high").substring(2));   // 最高气温
        weatherInfo.setLowTemp(result.getString("low").substring(2));     // 最低气温
        weatherInfo.setWeather(result.getString("type"));                 // 天气

        return weatherInfo;
    }

    /**
     * IP 解析 城市
     */
    public static String getCityByIp(String ip){
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            URL url = new URL(cityUrl+ip);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            // 设置读取流的编码格式,自定义编码
            InputStreamReader isr = new InputStreamReader(is, "gbk");
            reader = new BufferedReader(isr);
            String line = null;
            while((line = reader.readLine()) != null){
                sb.append(line + " ");
            }
            reader.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String addressStr="";
        String[] split = sb.toString().split(",");
        for(int i=0;i<split.length;i++){
            if(split[i].contains("city")){
                String[] split1 = split[i].split(":");
                if(split1[1].length()>1){
                    addressStr=split1[1].substring(1,split1[1].length()-1);
                    break;
                }
            }
        }
        return addressStr;
    }

}

  • 测试
public class Test {
 
    public static void main(String[] args){
        String info = WeatherUtils.GetWeatherData("天津");
        System.out.println("1.预测结果:" + info);                    // 全部天气数据,含预测
        WeatherInfo weatherinfo = WeatherUtils.GetWeather(info);
        System.out.println("2.今天天气:" + weatherinfo.toString());  // 当天天气数据
    }
 
}
  • 结果

预测结果

{undefined
    "data": {undefined
        "yesterday": {undefined
            "date": "9日星期一",
            "high": "高温 8℃",
            "fx": "东北风",
            "low": "低温 1℃",
            "fl": "<![CDATA[4-5级]]>",
            "type": "小雨"
        },
        "city": "天津",
        "forecast": [
            {undefined
                "date": "10日星期二",
                "high": "高温 13℃",
                "fengli": "<![CDATA[4-5级]]>",
                "low": "低温 3℃",
                "fengxiang": "西北风",
                "type": "晴"
            },
            {undefined
                "date": "11日星期三",
                "high": "高温 16℃",
                "fengli": "<![CDATA[4-5级]]>",
                "low": "低温 4℃",
                "fengxiang": "西南风",
                "type": "晴"
            },
            {undefined
                "date": "12日星期四",
                "high": "高温 16℃",
                "fengli": "<![CDATA[4-5级]]>",
                "low": "低温 2℃",
                "fengxiang": "东北风",
                "type": "多云"
            },
            {undefined
                "date": "13日星期五",
                "high": "高温 8℃",
                "fengli": "<![CDATA[3-4级]]>",
                "low": "低温 0℃",
                "fengxiang": "北风",
                "type": "多云"
            },
            {undefined
                "date": "14日星期六",
                "high": "高温 10℃",
                "fengli": "<![CDATA[4-5级]]>",
                "low": "低温 2℃",
                "fengxiang": "西北风",
                "type": "晴"
            }
        ],
        "ganmao": "天冷风大且昼夜温差也很大,易发生感冒,请注意适当增减衣服。",
        "wendu": "9"
    },
    "status": 1000,
    "desc": "OK"
}

今天天气

WeatherInfo{date='2020年03月10日', week=星期二, lunar='null', cityname='天津', weather='晴', temp='9', highTemp=' 13℃', lowTemp=' 3℃', tips='天冷风大且昼夜温差也很大,易发生感冒,请注意适当增减衣服。'}

预测结果:是该API获取的全部数据,包含昨天,今天,以及未来4天的天气情况;
今天天气:是从预测结果JSON数据中取出来,封装成对象的数据,在data.forecast下的第一条记录中。


参考链接:
https://blog.csdn.net/zhiwenganyong/article/details/122755057
https://blog.csdn.net/weixin_44259720/article/details/104768288

posted @   快乐小洋人  阅读(649)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示