JAVA實現天氣和地理位置識別以及隨機詩詞。
阿新 • • 發佈:2021-12-14
注意:API我選擇了隱藏
這裡是效果圖:
1 import org.json.JSONObject; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.net.URL; 8 9 public class Hello { 10 public static void main(String[] args) throws IOException {11 aries a=new aries(); 12 a.output(); 13 System.out.println("hello"); 14 //今日詩詞 15 InputStream in,in2; 16 in = new URL( "****" ).openStream();//此處為天氣API 17 try { 18 InputStreamReader inR = new InputStreamReader( in ); 19 BufferedReader buf = newBufferedReader( inR ); 20 String line; 21 StringBuilder sb=new StringBuilder(); 22 while ( ( line = buf.readLine() ) != null ) { 23 //System.out.println( line ); 24 sb.append(line); 25 } 26 JSONObject json = newJSONObject(sb.toString()); 27 JSONObject shi=json.getJSONObject("data").getJSONObject("origin"); 28 System.out.println("今日詩詞: "+json.getJSONObject("data").get("content")+"\n作者是:"+shi.get("author")+"\n"); 29 } finally { 30 in.close(); 31 } 32 33 //查詢天氣; 34 in2 = new URL( "****" ).openStream();//這裡是天氣API,自己找一個替換即可。 35 try { 36 InputStreamReader inR = new InputStreamReader( in2 ); 37 BufferedReader buf = new BufferedReader( inR ); 38 String line; 39 StringBuilder sb=new StringBuilder(); 40 while ( ( line = buf.readLine() ) != null ) { 41 //System.out.println( line ); 42 sb.append(line); 43 } 44 JSONObject json = new JSONObject(sb.toString()); 45 Object wjson=json.getJSONArray("HeWeather6").get(0); 46 JSONObject wzjson = new JSONObject(wjson.toString()).getJSONObject("basic"); 47 System.out.println("我找到你啦,你就在"+wzjson.get("location")+"。對波?"); 48 JSONObject wdjson = new JSONObject(wjson.toString()).getJSONObject("now"); 49 System.out.println("目前溫度為:"+wdjson.get("tmp")+"。 風向為"+wdjson.get("wind_dir")+"。"); 50 } finally { 51 in.close(); 52 } 53 54 } 55 } 56 //顏色一樣同一類元素。