Java天气查询源码(注释清楚)


import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;

public class WeatherDemo {
    public static void main(String[] args) throws Exception {
//            query("430100");//长沙

        //文件表示出来
        File file = new File("cityCode.txt");
        //2、流 输入流对象
        BufferedReader br = new BufferedReader(new FileReader(file));
        //3、一次读一行 读所有 循环 (执行多次) 最后null空
        String line = null;
        //4、使用HashMap
        HashMap hm = new HashMap();
        //5、向集合中添加数据
        hm.put("观塘区","810009");

        while ((line = br.readLine()) != null){
            //数据存储起来 容器  HashMap 键值对
            //字符串拆分 split
            String[] split = line.split("\t");
            hm.put(split[0], split[1]);
        }
        br.close();

        //输入一个城市
        System.out.println("输入一个城市的名字:");
        Scanner sc = new Scanner(System.in);
        String city = sc.next();

        //根据city 得到 对应的编号 hm
        String id = (String) hm.get(city);
        query(id);


        }

        public static <JSONObject, JSONArray> void query(String id) throws Exception {
            //查询天气   服务器的网址URL
            //https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户key>

            //1、创建一个URL网址对象
            URL url = new URL("https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=7c182e7cc89a8a8b809737b18c4ex79e");

            //2、从网址上  获取数据  下载
            //IO流   数据传输
            InputStream is = url.openStream();//打开网络流   得到流对象  最基础的输入流
            //3、将低级流一层一层包装成高级流  缓存流BuffererReader
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //4、br来读一行数据  一次读一行
            String line = br.readLine();
            //5、输出数据
            System.out.println(line);

      /*
        //得到更加直观的数据
        //1、解析line
        JSONObject object = JSONObject.fromObject(line);
        //2、通过object拿lives这个属性的  值
        JSONArray array = object.getJSONArray("lives");//得到的是一个json数组
        //json数组中 只有一个json对象  下标 0
        object = array.getJSONObject(0);
        //通过Object拿temperature的属性值
        String city = object.getString("city");
        String temperature = object.getString("temperature");
        System.out.println(city+"温度:"+temperature);
*/
        }
}

猜你喜欢

转载自blog.csdn.net/m0_72572822/article/details/128777273