使用TCP协议建立服务端使得访问时可以获取天气数据

个人练习项目,这个项目主要运用到网络方面的知识以及使用API获取天气

获取天气

首先需要去Members (openweathermap.org)这个网址注册获取APIKEY

然后写一个工具类获取天气信息,方法会返回一个字符串列表,上面有最近5天的信息,因为这个网站没有给我那么多天的,但是一天之内每个时间段的信息都有,可以拼接完url之后直接访问可以拿到返回的json格式数据,可以根据需要截取部分数据,我这里截取的是每一天中午12点的天气信息

public class WeatherForecast {

    private static final String API_KEY = "设置为自己的APIkey";
    private static final String API_URL = "https://api.openweathermap.org/data/2.5/forecast?q=city_name&appid=" + API_KEY ;//+ "&lang=zh_cn"如果想获取中文信息加上这个就好了


    public static List<String> getweather(String city) {

        try {
            URL url = new URL(API_URL.replace("city_name", city));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            System.out.println(url);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            StringBuilder response = new StringBuilder();
            while ((output = br.readLine()) != null) {
                response.append(output);
            }

            conn.disconnect();

            // 使用 Gson 解析 JSON 数据
            List<String> weatherForecast = parseWeatherForecast(response.toString());

            // 打印未来七天的天气预报
//            for (int i = 0; i < weatherForecast.size(); i++) {
//                System.out.println("Day " + (i + 1) + ": " + weatherForecast.get(i));
//            }
            return weatherForecast;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> parseWeatherForecast(String jsonResponse) {
        List<String> forecasts = new ArrayList<>();

        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);
        JsonArray list = jsonObject.getAsJsonArray("list");

        LocalDate currentDate = null;
        LocalDateTime noonDateTime = null;
        String noonWeather = null;

        for (JsonElement element : list) {
            JsonObject dayForecast = element.getAsJsonObject();

            // 提取日期和时间
            String dateTimeStr = dayForecast.get("dt_txt").getAsString();
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 如果是新的一天,或者已经到了下一个中午时间
            if (currentDate == null || currentDate.isBefore(dateTime.toLocalDate())) {
                // 保存前一天中午时间的天气信息
                if (currentDate != null && noonDateTime != null && noonWeather != null) {
                    String forecast = noonDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ": " + noonWeather;
                    forecasts.add(forecast);
                }

                // 更新当前日期和重置中午时间数据
                currentDate = dateTime.toLocalDate();
                noonDateTime = null;
                noonWeather = null;
            }

            // 如果是中午时间点
            if (dateTime.toLocalTime().equals(LocalTime.of(12, 0))) {
                noonDateTime = dateTime;
                JsonArray weatherArray = dayForecast.getAsJsonArray("weather");
                JsonObject weather = weatherArray.get(0).getAsJsonObject();
                noonWeather = weather.get("description").getAsString();
            }
        }
        // 添加最后一天中午时间的天气信息
        if (noonDateTime != null && noonWeather != null) {
            String forecast = noonDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ": " + noonWeather;
            forecasts.add(forecast);
        }
        return forecasts;
    }
}

创建服务端

这一步是创建了ServerSocket的对象然后指定端口等待客户端获取数据,然后将天气信息返回给客户端,其中还可以根据客户端发送的城市信息获取指定的天气信息,默认是发送北京的近五天信息,

public class NetServer {
    static Logger log = Logger.getLogger(NetServer.class.getName());

    public static void main(String[] args) throws IOException {
        // 创建服务端的对象
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(65201);
            log.info("已经绑定到端口" + ss.getLocalPort());
        } catch (IOException e) {
            log.severe("端口被占用");
            throw new RuntimeException(e);
        }

        // 等待数据
        log.info("等待数据中");
        Socket socket = ss.accept();
        // 设置超时时间为10秒(单位为毫秒)
        socket.setSoTimeout(3000);

        // 使用高速读写缓冲流
        BufferedReader bfd = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
        StringBuffer sb = new StringBuffer();
        int b;
        try {
            // 读取客户端发送的数据
            while ((b = bfd.read()) != -1) {
                sb.append((char) b);
            }
            log.info("获取到用户数据为" + sb);
        } catch (SocketTimeoutException e) {
            // 客户端超时处理
            sb.append("BeiJing");
        }

        // 返回天气信息
        OutputStream os = socket.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        String reply = "以下是" + sb.toString() + "近五日的天气\n";
        writer.write(reply);

        List<String> weatherForecast = WeatherForecast.getweather(sb.toString());
        if (weatherForecast != null) {
            for (int i = 0; i < weatherForecast.size(); i++) {
                writer.write("Day " + (i + 1) + ": " + weatherForecast.get(i) + "\n");
            }
        }
        writer.write("以上数据由openweathermap提供");

        log.info("数据返回成功");
        // 刷新缓冲区并关闭连接
        writer.flush();
        socket.close();
        ss.close();
    }
}

 创建客户端

        注释部分是发送数据的方式,也可以不发,使用127.0.0.1用本机做为发送请求的ip

public class NetClient {
    public static void main(String[] args) throws IOException {
        // 创建socket对象
        Socket socket = new Socket("127.0.0.1", 65201);

//        OutputStream os = socket.getOutputStream();
//        os.write("hengyang".getBytes());
//        socket.shutdownOutput();
        // 读回写数据
        BufferedReader bfd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line = bfd.readLine()) != null) {
            System.out.println(line);
        }
        socket.close();
    }
}

测试效果

        注意先运行服务端再运行客户端,后期可以上线阿里云实现多方访问,这里只能本地后者同局域网内的主机可以访问,上线阿里云的访问方法以后再写一篇文章给出

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值