WeatherService.java 5.45 KB
package com.glsk.service;

import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

@Service
public class WeatherService {
    private final String baseUrl = "https://nj59faynve.re.qweatherapi.com";
    private final String apiKey = "fbe83962adc34e80885c9cac5a885d35";


    @Tool(description = "通过城市Id实时获取天气")
    public String getRealTimeWeather(String cityId) {
        StringBuilder response = new StringBuilder();

        try {
            String urlString = String.format("%s/v7/weather/now?location=%s&key=%s", baseUrl, cityId, apiKey);
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 设置请求属性,模拟浏览器
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Accept-Encoding", "gzip,deflate");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                // 获取响应流并根据 Content-Encoding 判断是否需要解压缩
                String encoding = connection.getContentEncoding();
                BufferedReader reader;

                if ("gzip".equalsIgnoreCase(encoding)) {
                    // 如果是 gzip 压缩,使用 GZIPInputStream 解压缩
                    reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
                } else if ("deflate".equalsIgnoreCase(encoding)) {
                    // 如果是 deflate 压缩,使用 InflaterInputStream 解压缩
                    reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(connection.getInputStream())));
                } else {
                    // 没有压缩,直接读取
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                }

                String inputLine;
                while ((inputLine = reader.readLine()) != null) {
                    response.append(inputLine);
                }
                reader.close();
            } else {
                System.out.println("GET request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }


    @Tool(description = "根据城市Id获取未来三天的天气预报")
    public String getForecastWeather(String cityId) {
        StringBuilder response = new StringBuilder();
        try {
            String urlString = String.format("%s/v7/weather/3d?location=%s&key=%s", baseUrl, cityId, apiKey);
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 设置请求属性,模拟浏览器
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Accept-Encoding", "gzip,deflate");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                // 获取响应流并根据 Content-Encoding 判断是否需要解压缩
                String encoding = connection.getContentEncoding();
                BufferedReader reader;

                if ("gzip".equalsIgnoreCase(encoding)) {
                    // 如果是 gzip 压缩,使用 GZIPInputStream 解压缩
                    reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
                } else if ("deflate".equalsIgnoreCase(encoding)) {
                    // 如果是 deflate 压缩,使用 InflaterInputStream 解压缩
                    reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(connection.getInputStream())));
                } else {
                    // 没有压缩,直接读取
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                }

                String inputLine;
                while ((inputLine = reader.readLine()) != null) {
                    response.append(inputLine);
                }
                reader.close();
                System.out.println("Response Body: " + response.toString());
            } else {
                System.out.println("GET request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }

    public static void main(String[] args) {
        WeatherService weatherService = new WeatherService();
        String realTimeWeather = weatherService.getRealTimeWeather("101010100");
        System.out.println(realTimeWeather);
    }

}