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
测试类
public static void main(String[] args){ String msg = ""; GetWeatherMain getWeatherMain = new GetWeatherMain(); List> 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); }