1. 程式人生 > 其它 >Java實現天氣預報

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);
}