通过城市获取全球天气信息,简单操作上线,Java

1,107 阅读3分钟

前言

之前做过获取天气数据,到前端展示的,排查了一些第三方支持的,后面使用OpenWeather。在这记录分享下,给大家参考参考。

(我是后半夜Java,在掘金这分享下经验,那些靠copy的搬运作者,未经允许,不要copy文章了)

好处:免费的量够用,简单用邮箱注册就可以,不够就注册十来个key,在代码里逻辑循环去用。 缺点:入参是城市名,有的会查询不到,查询不到就只能走一些兜底策略了。

接口支持描述

这是翻译后的截图: image.png

我们先看下当前天气的

当前天气

image.png

按地理坐标

api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=[{API key}](https://home.openweathermap.org/api_keys)

按城市ID

api.openweathermap.org/data/2.5/weather?id={city id}&appid=[{API key}](https://home.openweathermap.org/api_keys) 城市ID可以直接从他这地方下载

image.png

当然可以支持批量的。

返回对象

那么重点关注就是返回的数据结构了:


{
  "coord": {
    "lon": -122.08,
    "lat": 37.39
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 282.55,
    "feels_like": 281.86,
    "temp_min": 280.37,
    "temp_max": 284.26,
    "pressure": 1023,
    "humidity": 100
  },
  "visibility": 16093,
  "wind": {
    "speed": 1.5,
    "deg": 350
  },
  "clouds": {
    "all": 1
  },
  "dt": 1560350645,
  "sys": {
    "type": 1,
    "id": 5122,
    "message": 0.0139,
    "country": "US",
    "sunrise": 1560343627,
    "sunset": 1560396563
  },
  "timezone": -25200,
  "id": 420006353,
  "name": "Mountain View",
  "cod": 200
  }                         

                        

重点看下描述,这个直观看出对你是否有用

```- coord

-   `coord.lon` 城市地理位置、经度
-   `coord.lat` 城市地理位置、纬度
  • weather (更多信息天气条件代码)

    • weather.id 天气状况 ID
    • weather.main 一组天气参数(雨、雪、极端等)
    • weather.description组内天气状况。您可以获得您的语言的输出。了解更多
    • weather.icon 天气图标 ID
  • base 内部参数

  • main

    • main.temp温度。单位默认值:开尔文,公制:摄氏度,英制:华氏度。
    • main.feels_like温度。该温度参数说明了人类对天气的感知。单位默认值:开尔文,公制:摄氏度,英制:华氏度。
    • main.pressure 大气压力(在海平面上,如果没有 sea_level 或 grnd_level 数据),hPa
    • main.humidity 湿度, %
    • main.temp_min目前最低温度。这是目前观察到的最低温度(在大型特大城市和城市地区)。单位默认值:开尔文,公制:摄氏度,英制:华氏度。
    • main.temp_max目前最高温度。这是目前观测到的最高温度(在大型特大城市和城市地区)。单位默认值:开尔文,公制:摄氏度,英制:华氏度。
    • main.sea_level 海平面上的大气压力,hPa
    • main.grnd_level 地面大气压力,hPa
  • wind

    • wind.speed风速。单位默认值:米/秒,公制:米/秒,英制:英里/小时。
    • wind.deg 风向,度数(气象)
    • wind.gust阵风。单位默认:米/秒,公制:米/秒,英制:英里/小时
  • clouds

    • clouds.all 云量,%
  • rain

    • rain.1h 过去 1 小时的降雨量,毫米
    • rain.3h 过去 3 小时的降雨量,毫米
  • snow

    • snow.1h 过去 1 小时的雪量,毫米
    • snow.3h 过去 3 小时的雪量,毫米
  • dt 数据计算时间,unix,UTC

  • sys

    • sys.type 内部参数
    • sys.id 内部参数
    • sys.message 内部参数
    • sys.country 国家代码(GB、JP 等)
    • sys.sunrise 日出时间,unix,UTC
    • sys.sunset 日落时间,unix,UTC
  • timezone 以秒为单位从 UTC 偏移

  • id 城市编号

  • name 城市名称

  • cod 内部参数



调用的代码逻辑:
HttpResponse<String> stringHttpResponse = Unirest.get(weatherUrl + "/weather").queryString("lang", lang).queryString("units", units).queryString("q", city).queryString("appid", weatherKey).asString();
String body = stringHttpResponse.getBody();

总结

这个第三方天气还是能够满足日常需求,特别他是全球的。