java如何获取天气 java调用天气接口_开发语言

接口地址:http://apis.juhe.cn/simpleWeather/query

返回格式:json

请求方式:http get/post

请求示例:http://apis.juhe.cn/simpleWeather/query?city=%E8%8B%8F%E5%B7%9E&key=

接口备注:通过城市名称或城市ID查询天气预报情况

请求参数说明:

名称

必填

类型

说明

city


string

要查询的城市名称/id,城市名称如:温州、上海、北京,需要utf8 urlencode

key


string

在个人中心->我的数据,接口名称上方查看

返回参数说明:

名称

类型

说明

error_code

int

返回码,0为查询成功

reason

string

返回说明

result

string

返回结果集

-

-

-

realtime

-

当前天气详情情况

info

string

天气情况,如:晴、多云

wid

string

天气标识id,可参考小接口2

temperature

string

温度,可能为空

humidity

string

湿度,可能为空

direct

string

风向,可能为空

power

string

风力,可能为空

aqi

string

空气质量指数,可能为空

-

-

-

future

-

近5天天气情况

date

string

日期

temperature

string

温度,最低温/最高温

weather

string

天气情况

direct

string

风向

JSON返回示例:

{
    "reason": "查询成功",
    "result": {
        "city": "苏州",
        "realtime": {
            "temperature": "4",
            "humidity": "82",
            "info": "阴",
            "wid": "02",
            "direct": "西北风",
            "power": "3级",
            "aqi": "80"
        },
        "future": [
            {
                "date": "2019-02-22",
                "temperature": "1/7℃",
                "weather": "小雨转多云",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": "北风转西北风"
            },
            {
                "date": "2019-02-23",
                "temperature": "2/11℃",
                "weather": "多云转阴",
                "wid": {
                    "day": "01",
                    "night": "02"
                },
                "direct": "北风转东北风"
            },
            {
                "date": "2019-02-24",
                "temperature": "6/12℃",
                "weather": "多云",
                "wid": {
                    "day": "01",
                    "night": "01"
                },
                "direct": "东北风转北风"
            },
            {
                "date": "2019-02-25",
                "temperature": "5/12℃",
                "weather": "小雨转多云",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": "东北风"
            },
            {
                "date": "2019-02-26",
                "temperature": "5/11℃",
                "weather": "多云转小雨",
                "wid": {
                    "day": "01",
                    "night": "07"
                },
                "direct": "东北风"
            }
        ]
    },
    "error_code": 0
}

1、开通接口

天气预报接口服务使用的聚合数据提供的免费接口,每天可以100次免费调用。可以通过https://www.juhe.cn/docs/api/id/73注册及开通。

2、通过Java发起城市天气查询

import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class SimpleWeather {
    // 天气情况查询接口地址
    public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";
    // 接口请求Key
    public static String API_KEY = "xxxxxxxxxxxxxx";

    public static void main(String[] args) {
        String cityName = "北京";
        queryWeather(cityName);
    }

    /**
     * 根据城市名查询天气情况
     *
     * @param cityName
     */
    public static void queryWeather(String cityName) {
        Map<String, Object> params = new HashMap<>();//组合参数
        params.put("city", cityName);
        params.put("key", API_KEY);
        String queryParams = urlencode(params);

        String response = doGet(API_URL, queryParams);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");

                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject realtime = result.getJSONObject("realtime");

                System.out.printf("城市:%s%n", result.getString("city"));
                System.out.printf("天气:%s%n", realtime.getString("info"));
                System.out.printf("温度:%s%n", realtime.getString("temperature"));
                System.out.printf("湿度:%s%n", realtime.getString("humidity"));
                System.out.printf("风向:%s%n", realtime.getString("direct"));
                System.out.printf("风力:%s%n", realtime.getString("power"));
                System.out.printf("空气质量:%s%n", realtime.getString("aqi"));
            } else {
                System.out.println("调用接口失败:" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流,并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}