Java实现天气预报

通过Java实现天气预报,该方法必须联网


GetWeather

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class GetWeather {
    public static String getResult(String url) {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse response = httpClient.execute(new HttpGetConfig(url))) {
            String result = EntityUtils.toString(response.getEntity(),"utf-8"); //设置编码,防止乱码
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}

class HttpGetConfig extends HttpGet {
    public HttpGetConfig(String url) {
        super(url);
        setDefaultConfig();
    }

    private void setDefaultConfig() {
        this.setConfig(RequestConfig.custom()
                .setConnectionRequestTimeout(1000 * 10)
                .setConnectTimeout(1000 * 10)
                .setSocketTimeout(1000 * 10)
                .build());
        this.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0");
    }
}

GetWeatherMain

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class GetWeatherMain {
//    public static void main(String[] args) {
//        GetWeatherMain htmlUtilTest= new GetWeatherMain();
//        htmlUtilTest.searchWeather("101110200");
//    }

    /**
     *
     * @param
     * @return 获取未来7天的天气预报
     */
    public List<Map<String,String>> searchWeather(String id){
        String result= GetWeather.getResult("http://www.weather.com.cn/weather/"+id+".shtml");
        Document document= Jsoup.parse(result);
        Elements elements;

        // 获取日期和星期
        elements=document.select("h1");
        List<String> dateList=new ArrayList<>();
        List<String> dayList=new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            String text=elements.get(i).text();
            int length=text.length();
            dateList.add(text.substring(0,length-4));
            dayList.add(text.substring(length-3,length-1));
        }
        //System.out.println(dateList);
        //System.out.println(dayList);

        // 获取天气
        elements=document.select("p[class=wea]");
        List<String> weatherList=new ArrayList<>();
        for (Element item : elements) {
            weatherList.add(item.text());
        }
        //System.out.println(weatherList);

        // 获取温度,最高温和最低温
        elements=document.select("p[class=tem]");
        int i=0;
        List<String> highTempList=new ArrayList<>();
        List<String> lowTempList=new ArrayList<>();
        for (Element item : elements) {
            highTempList.add(item.select("span").text()+"℃");
            lowTempList.add(item.select("i").text());
        }
        //System.out.println(highTempList);
        //System.out.println(lowTempList);


        // 封装结果,每天一行,未来7天
        List<Map<String,String>> list=new ArrayList<>();
        for (int j = 0; j < 7; j++) {
            Map<String,String> map=new LinkedHashMap<>();
            map.put("日期",dateList.get(j));
            map.put("day",dayList.get(j));
            map.put("天气",weatherList.get(j));
            map.put("最高温度",highTempList.get(j));
            map.put("最底温度",lowTempList.get(j));

            list.add(map);
        }
        //list.forEach(System.out::println);

        return list;
    }
}

测试类

public static void main(String[] args){
    String msg = "";
    GetWeatherMain getWeatherMain = new GetWeatherMain();
    List<Map<String,String>> list = getWeatherMain.searchWeather("101240101");          //这里需要传入城市ID,可以通过该链接进行查看https://blog.csdn.net/WXB_gege/article/details/106853189
    msg = "【南昌地区天气预报】\n"+ list.get(0).toString() +"\n"+ "-----------------------------" + "\n" + list.get(1).toString();   //这里只获取两天的天气预报
    msg = msg.replace('=',':').replace('{',' ').replace('}',' ').replace(',','\n');
    System.out.println(msg);
}

 

posted @ 2022-03-07 17:01  RFAA  阅读(834)  评论(0编辑  收藏  举报