Java获取天气情况

该博客介绍了如何在项目中通过高德开放平台的天气查询接口获取天气信息。作者详细展示了申请API Key的步骤,并提供了Java代码示例来调用接口,解析JSON响应以获取天气详情,包括天气、最高/最低温度和风力风向等。同时,指出了在不同JDK版本下处理编码问题的注意事项。
摘要由CSDN通过智能技术生成

背景:项目中有个需求是根据行政区划编码获取当天天气情况,于是开始在网上找各种API,但是经过测试发现不是接口返回值乱码就是接口经常挂掉,后来经过多方搜索发现高德开放平台的天气查询接口很好用,

地址:https://lbs.amap.com/api/webservice/guide/api/weatherinfo 

一、注册登录高德开放平台账户

创建好应用后,点击添加按钮,为应用添加一个key值,名字随便起

到这步,key值就申请好了

二、根据API编写调用代码

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * <p>
 * <p>Title:GoodWeatherUtil.java</p >
 * <p>Description: </p >
 * <p>Date:2020/12/21 18:26</p >
 *
 * @author wsh
 * @version 1.0
 */
public class GoodWeatherUtil {
    private static final String WEATHER_SERVICES_URL = "https://restapi.amap.com/v3/weather/weatherInfo?city=";
    private static final String WEATHER_KEY = "&key=e340f838515bdbd73678ee4c8fb7782d&extensions=all";


    public static String getWeatherData(String cityCode){
        int codelength = cityCode.length();
        if (6 != codelength){
            return "500";
        }
        StringBuffer sb = new StringBuffer();
        try {
            String weather_url = WEATHER_SERVICES_URL+cityCode+WEATHER_KEY;
            URL url = new URL(weather_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            connection.connect();
            //读取URL的响应
            //BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + " ");
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }

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

        //从json数据中提取数据
        JSONArray forecasts = dataOfJson.getJSONArray("forecasts");
        JSONObject result = forecasts.getJSONObject(0);
        JSONArray casts = result.getJSONArray("casts");

        //取得当天的
        JSONObject weather = casts.getJSONObject(0);
        weatherInfo.setWeatherInfo(weather.getString("dayweather"));
        String high = weather.getString("daytemp");
        weatherInfo.setMaxTemperature(Integer.parseInt(high));
        String low = weather.getString("nighttemp");
        weatherInfo.setMinTemperature(Integer.parseInt(low));
        String fengli = weather.getString("daypower");
        String fengxiang = weather.getString("daywind");
        StringBuffer windPower = new StringBuffer();
        windPower.append(fengxiang).append("风").append(fengli).append("级");
        weatherInfo.setWindPower(windPower.toString());
        return weatherInfo;
    }
}
/**
 * <p>
 * <p>Title:WeatherInfo.java</p >
 * <p>Description:天气实体类 </p >
 * <p>Date:2020/12/21 16:14</p >
 *
 * @author wsh
 * @version 1.0
 */
public class WeatherInfo {
    private String weatherInfo;//天气
    private Integer maxTemperature;//最高气温
    private Integer minTemperature;//最低气温
    private String windPower;//风力风向


    public String getWeatherInfo() {
        return weatherInfo;
    }

    public void setWeatherInfo(String weatherInfo) {
        this.weatherInfo = weatherInfo;
    }

    public Integer getMaxTemperature() {
        return maxTemperature;
    }

    public void setMaxTemperature(Integer maxTemperature) {
        this.maxTemperature = maxTemperature;
    }

    public Integer getMinTemperature() {
        return minTemperature;
    }

    public void setMinTemperature(Integer minTemperature) {
        this.minTemperature = minTemperature;
    }

    public String getWindPower() {
        return windPower;
    }

    public void setWindPower(String windPower) {
        this.windPower = windPower;
    }

    @Override
    public String toString() {
        return "WeatherInfo{" +
                "weatherInfo='" + weatherInfo + '\'' +
                ", maxTemperature=" + maxTemperature +
                ", minTemperature=" + minTemperature +
                ", windPower='" + windPower + '\'' +
                '}';
    }
}

测试代码如下:

public class App {

    public static void main(String [] args) {
        String weatherData = GoodWeatherUtil.getWeatherData("110000");
        System.out.println(weatherData);
        WeatherInfo weatherInfo = GoodWeatherUtil.GetWeather(weatherData);
        System.out.println(weatherInfo);
    }
}

运行结果:

特别提示:假如使用的jdk是1.8的,代码中的如下代码不用设置编码,可以去掉utf-8的设置,假如使用的是jdk1.7必须要设置这个编码,不然调用API出来的是乱码

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值