当前位置: 首页> 健康> 科研 > 【Android】使用和风天气API获取天气数据吧!(天气预报系列之一)

【Android】使用和风天气API获取天气数据吧!(天气预报系列之一)

时间:2025/8/23 8:37:05来源:https://blog.csdn.net/2301_79344902/article/details/142034161 浏览次数:0次

【Android】使用和风天气API获取天气数据吧!(天气预报系列之一)

古话说得好,要有天气预报,首先需要有天气,和预报。

今天给大家介绍一个好用的天气预报API:和风天气。以及webAPI的使用方法~(和风天气打钱)

和风天气网址:和风天气 | 商业气象服务商, 天气预报,灾害预警,台风路径,卫星云图,天气API/SDK/APP, 天气插件, 历史天气, 气象可视化 (qweather.com)

(广告位招租)

首先我们需要注册一个和风天气账号(要不干脆从盘古开天辟地开始讲?)

点击这个,进入api的控制台。

image-20240908210034448

点击这个,进入项目管理。

image-20240908210119450

而后创建项目。

image-20240908214732418

按图设置即可,首先设置项目名称,而后设置免费订阅(这里免费订阅不可以选是因为笔者已经创建过一个免费订阅的项目)

最后设置Key为Web API,那可能有同学要问了,既然是Android的项目,为什么不用Android SDK呢?

(不用Web API怎么练习okHttp?)

配置好了之后我们可以得到:

image-20240908214945169

当当~

直接点击KEY下方的查看就可以找到你的KEY啦,这个KEY主要是用于计算账户请求次数的,和风天气一天一千次还是很容易用完的,大家写项目的时候一定要记得别写死循环,一下子把天气请求次数用光了。

项目当中

完成了上述操作,我们就可以进入Android Studio,写一个天气请求的工具类。

我们边进入编译器,边打开和风天气的开发文档。

image-20240908215918244

网络请求的发出,首先要拼接一个URL字符串。字符串的可选参数如上。

首先定义好KEY和基础的URL:

private static final String KEY = "114514";private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/";

而后开始写方法:

我这里使用OkHttp作为请求类:

public static String getNowWeatherInfo(String locationID) {String resultResponse = "";String locationUrl = BASE_URL + "now" + "?" + "key=" + KEY + "&" +"location=" + locationID+ "&" + "lang=" + "en";OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(locationUrl).build();try {Response response = client.newCall(request).execute();if (response.isSuccessful()) {resultResponse = response.body().string();Log.d(TAG, "getNowWeatherInfo: " + resultResponse);}} catch (IOException e) {Log.d(TAG, "getNowWeatherInfo: yichang");}return resultResponse;}
  1. 初始化变量
    • 初始化一个空字符串resultResponse,用于存储从API获取的天气信息。
  2. 构建请求URL
    • 构建一个请求URL,这个URL由基础URL(BASE_URL),API的端点(now),以及查询参数组成。查询参数包括API密钥(KEY),地点ID(locationID),以及请求的语言(en表示英语)。
  3. 创建HTTP客户端
    • 创建一个OkHttpClient实例,用于发起网络请求。
  4. 构建请求对象
    • 使用OkHttpClient构建一个Request对象,指定要请求的URL。
  5. 发起网络请求
    • 使用try块来捕获可能发生的IOException
    • 通过OkHttpClient发起网络请求,并获取响应。
  6. 处理响应
    • 检查响应是否成功(response.isSuccessful())。
    • 如果响应成功,将响应体的内容转换为字符串,并存储在resultResponse变量中。
    • 记录响应结果到日志中。
  7. 异常处理
    • 如果在请求过程中发生IOException,捕获异常并记录异常信息到日志中。
  8. 返回结果
    • 返回resultResponse变量,它包含了从API获取的天气信息。如果请求失败,返回的将是空字符串。
  9. 结束方法
    • 方法执行完毕,返回获取的天气信息或空字符串。

依葫芦画瓢,可以画出以下几个方法:

public static String getHourlyWeatherInfo(String locationID) {String resultResponse = "";String locationUrl = BASE_URL + "24h" + "?" + "key=" + KEY + "&" +"location=" + locationID;OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(locationUrl).build();try {Response response = client.newCall(request).execute();if (response.isSuccessful()) {resultResponse = response.body().string();Log.d(TAG, "getHourlyWeatherInfo: " + resultResponse);}} catch (IOException e) {Log.d(TAG, "getHourlyWeatherInfo: yichang");}return resultResponse;}public static String getDailyWeatherInfo(String locationID) {String resultResponse = "";String locationUrl = BASE_URL + "7d" + "?" + "key=" + KEY + "&" +"location=" + locationID+ "&" + "lang=" + "en";;OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(locationUrl).build();try {Response response = client.newCall(request).execute();if (response.isSuccessful()) {resultResponse = response.body().string();Log.d(TAG, "getDailyWeatherInfo: " + resultResponse);}} catch (IOException e) {Log.d(TAG, "getDailyWeatherInfo: yichang");}return resultResponse;}

分别对应按小时计数的天气和按天的天气。

有了网络请求,网络请求返回的是个Json字符串呐。

image-20240908220201316

我们还需要写一个JSON字符串的解析类。

说干就干:

此处以解析当前天气Json为例。

public static NowWeatherInfo parseNowWeatherJson(String jsonStr) {NowWeatherInfo info = null;try {JSONObject locationJson = new JSONObject(jsonStr);String nowJson = locationJson.optString("now");Gson gson = new Gson();info = gson.fromJson(String.valueOf(nowJson), NowWeatherInfo.class);Log.d(TAG, "parseJsonData: " + nowJson);} catch (JSONException e) {Log.d(TAG, "parseJsonData: 解析Json数据失败");}return info;}

在这里,我们使用了Gson解析。Gson对应的类放在下面。

public class NowWeatherInfo {private String temp; // 温度private String feelsLike; // 体感温度private String icon; // 天气图标代码private String text; // 天气状况文本private String wind360; // 风向360度private String windDir; // 风向private String windScale; // 风力等级private String windSpeed; // 风速private String humidity; // 湿度private String precip; // 降水量private String pressure; // 气压private String vis; // 能见度private String cloud; // 云量private String dew; // 露点温度public String getTemp() {return temp;}public void setTemp(String temp) {this.temp = temp;}public String getFeelsLike() {return feelsLike;}public void setFeelsLike(String feelsLike) {this.feelsLike = feelsLike;}public String getIcon() {return icon;}public void setIcon(String icon) {this.icon = icon;}public String getText() {return text;}public void setText(String text) {this.text = text;}public String getWind360() {return wind360;}public void setWind360(String wind360) {this.wind360 = wind360;}public String getWindDir() {return windDir;}public void setWindDir(String windDir) {this.windDir = windDir;}public String getWindScale() {return windScale;}public void setWindScale(String windScale) {this.windScale = windScale;}public String getWindSpeed() {return windSpeed;}public void setWindSpeed(String windSpeed) {this.windSpeed = windSpeed;}public String getHumidity() {return humidity;}public void setHumidity(String humidity) {this.humidity = humidity;}public String getPrecip() {return precip;}public void setPrecip(String precip) {this.precip = precip;}public String getPressure() {return pressure;}public void setPressure(String pressure) {this.pressure = pressure;}public String getVis() {return vis;}public void setVis(String vis) {this.vis = vis;}public String getCloud() {return cloud;}public void setCloud(String cloud) {this.cloud = cloud;}public String getDew() {return dew;}public void setDew(String dew) {this.dew = dew;}@Overridepublic String toString() {return "NowWeatherDataBean{" +"temp='" + temp + '\'' +", feelsLike='" + feelsLike + '\'' +", icon='" + icon + '\'' +", text='" + text + '\'' +", wind360='" + wind360 + '\'' +", windDir='" + windDir + '\'' +", windScale='" + windScale + '\'' +", windSpeed='" + windSpeed + '\'' +", humidity='" + humidity + '\'' +", precip='" + precip + '\'' +", pressure='" + pressure + '\'' +", vis='" + vis + '\'' +", cloud='" + cloud + '\'' +", dew='" + dew + '\'' +'}';}
}

结语

天气预报仅仅有数据肯定不够,至于UI等等后事如何,且听第二三四五六回分解。

关键字:【Android】使用和风天气API获取天气数据吧!(天气预报系列之一)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: