package com.muyu.cloud.mart.config;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @Author：chaiyapeng
 * @Package：com.muyu.cloud.mart.config
 * @Project：cloud-mart
 * @name：WeatherInterface
 * @Date：2024/8/23 10:11
 * 气象预警接口
 */
public class WeatherInterface {
    public static void main(String[] args) throws Exception {
        String apiKey = "80e78ee9adaded8b1f42ec9cbdf69ac9";
        String apiUrl = "https://apis.juhe.cn/fapig/alarm/citys";

        HashMap<String, String> map = new HashMap<>();
        map.put("key", apiKey);

        URL url = new URL(String.format(apiUrl + "?" + params(map)));
        BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response);
    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
}
