1. 程式人生 > >和風天氣獲取天氣相關資料

和風天氣獲取天氣相關資料

和風天氣api說明地址: http://www.heweather.com/documents/api/s6

專案需要用到天氣的資料來做測試,所以學習了一下和風天氣這個平臺的使用方法,個人覺得還是很全面的。

使用之前需要自己在和風天氣平臺上面註冊一個使用者,然後點選控制器複製一下自己的key,後面會用到。

 程式碼:

我獲取的就是今天明天和後天三天的天氣加上pm2.5,看過開發文件就知道pm2.5是在另外一個api上面,所以我就需要兩個api介面

// 介面地址
	private String API = "https://free-api.heweather.com/s6/weather?key=加上你自己的key&location=";
	// 獲取Pm25的介面地址
	private String getPm25URL = "https://free-api.heweather.com/s6/air/now?key=加上你自己的key&location=";

 介面的形式也很簡單,就是

https://free-api.heweather.com/s6/weather?key=key&location=

需要注意的是:https://free-api.heweather.com/s6/weather?key= 這一段,不是所有人都是一樣的,,就是你自己需要哪種資料就去找對應的api,因為我自己就是去看別人的程式碼然後提示,某個屬性不存在,,233,然後key也是每個人不一樣的,key和location都是必須的值。location是中文的話需要處理亂碼。只需要處理location。

 Java程式碼:

因為這個是為了測試不同地方的資料是否一致然後又不能開車到那個地方去,所以需要輸入地名,然後可以輸入的地名平臺上面也有,http://www.heweather.com/documents/city

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		binID();

		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				String city = editText.getText().toString();
				String c = "";
				try {
					// 解決輸入的地址是中文的情況
					c = URLEncoder.encode(city, "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				new MyWeather().execute(API + c);
				new getPm25().execute(getPm25URL + c);
			}
		});
	}

	class MyWeather extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... strings) {
			StringBuffer stringBuffer = null;// 相當於一個 字串,只不過執行緒更安全

			try {
				URL url = new URL(strings[0]);
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();
				InputStream inputStream = null;// 獲取要輸入的資料
				if (httpURLConnection.getResponseCode() == 200) {
					// 接收結果
					inputStream = httpURLConnection.getInputStream();
					// 檢測網路異常
				} else {
					return "11";
				}
				InputStreamReader reader = new InputStreamReader(inputStream,
						"UTF-8");// 讀取輸入的資料,解決亂碼
				BufferedReader bufferedReader = new BufferedReader(reader);// 快取流
				stringBuffer = new StringBuffer();
				String timp = null;
				// 緩衝逐行讀取
				while ((timp = bufferedReader.readLine()) != null) {
					stringBuffer.append(timp);
				}
				// 關閉流
				inputStream.close();
				reader.close();
				bufferedReader.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return stringBuffer.toString();
		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			if (s.equals("11")) {
				Toast.makeText(MainActivity.this, "網路異常", Toast.LENGTH_SHORT)
						.show();
			}
			try {
				JSONObject object = new JSONObject(s);
				JSONObject object1 = object.getJSONArray("HeWeather6")
						.getJSONObject(0);
				// 獲取未來三天的溫度天氣日期
				JSONObject obj0 = null;
				JSONObject obj1 = null;
				JSONObject obj2 = null;
				// 預報的三天
				JSONArray daily_forecast = object1
						.getJSONArray("daily_forecast");
				obj0 = daily_forecast.getJSONObject(0);// 今天的
				tv_today_date.setText("今天日期:" + obj0.getString("date"));
				tv_today_temperature.setText("今天溫度:"
						+ obj0.getString("tmp_min") + "~"
						+ obj0.getString("tmp_max"));
				tv_today_weatherName.setText("今天天氣:"
						+ obj0.getString("cond_txt_d") + "~"
						+ obj0.getString("cond_txt_n"));// 這個天氣狀況可能會有兩種,白天跟晚上不同,是都要顯示出來嗎
				obj1 = daily_forecast.getJSONObject(1);// 明天的
				tv_tomorrow_date.setText("明天日期:" + obj1.getString("date"));
				tv_tomorrow_temperature.setText("明天溫度:"
						+ obj1.getString("tmp_min") + "~"
						+ obj1.getString("tmp_max"));
				tv_tomorrow_weatherName.setText("明天天氣:"
						+ obj1.getString("cond_txt_d") + "~"
						+ obj1.getString("cond_txt_n"));
				obj2 = daily_forecast.getJSONObject(2);// 後天的
				tv_dayaftertomorrow_date.setText("後天日期:"
						+ obj2.getString("date"));
				tv_dayaftertomorrow_temperature.setText("後天溫度:"
						+ obj2.getString("tmp_min") + "~"
						+ obj2.getString("tmp_max"));
				tv_dayaftertomorrow_weatherName.setText("後天天氣:"
						+ obj2.getString("cond_txt_d") + "~"
						+ obj2.getString("cond_txt_n"));
				// 實時的天氣
				JSONObject now = object1.getJSONObject("now");
				tv_now_temperature.setText("實時溫度:" + now.getString("tmp"));// 兩個溫度貌似是一樣的
				tv_now_weatherName
						.setText("實時 天氣:" + now.getString("cond_txt"));

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void binID() {
		editText = (EditText) findViewById(R.id.main_editView);
		button = (Button) findViewById(R.id.main_button);

		tv_now_temperature = (TextView) findViewById(R.id.tv_now_temperature);
		tv_now_weatherName = (TextView) findViewById(R.id.tv_now_weatherName);
		tv_now_pm2_5 = (TextView) findViewById(R.id.tv_now_pm2_5);

		tv_today_date = (TextView) findViewById(R.id.tv_today_date);
		tv_today_temperature = (TextView) findViewById(R.id.tv_today_temperature);
		tv_today_weatherName = (TextView) findViewById(R.id.tv_today_weatherName);
		// tv_today_PM2_5 = (TextView) findViewById(R.id.tv_today_PM2_5);

		tv_tomorrow_date = (TextView) findViewById(R.id.tv_tomorrow_date);
		tv_tomorrow_temperature = (TextView) findViewById(R.id.tv_tomorrow_temperature);
		tv_tomorrow_weatherName = (TextView) findViewById(R.id.tv_tomorrow_weatherName);
		// tv_tomorrow_PM2_5 = (TextView) findViewById(R.id.tv_tomorrow_PM2_5);

		tv_dayaftertomorrow_date = (TextView) findViewById(R.id.tv_dayaftertomorrow_date);
		tv_dayaftertomorrow_temperature = (TextView) findViewById(R.id.tv_dayaftertomorrow_temperature);
		tv_dayaftertomorrow_weatherName = (TextView) findViewById(R.id.tv_dayaftertomorrow_weatherName);
		// tv_dayaftertomorrow_PM2_5 = (TextView)
		// findViewById(R.id.tv_dayaftertomorrow_PM2_5);
	}

	class getPm25 extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			StringBuffer stringBuffer = null;

			try {
				URL url = new URL(params[0]);
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();
				InputStream inputStream = null;
				if (httpURLConnection.getResponseCode() == 200) {
					// 接收結果
					inputStream = httpURLConnection.getInputStream();
					// 檢測網路異常
				} else {
					return "11";
				}
				InputStreamReader reader = new InputStreamReader(inputStream,
						"UTF-8");
				BufferedReader bufferedReader = new BufferedReader(reader);
				stringBuffer = new StringBuffer();
				String timp = null;
				// 緩衝逐行讀取
				while ((timp = bufferedReader.readLine()) != null) {
					stringBuffer.append(timp);
				}
				// 關閉流
				inputStream.close();
				reader.close();
				bufferedReader.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return stringBuffer.toString();
		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			if (s.equals("11")) {
				Toast.makeText(MainActivity.this, "網路異常", Toast.LENGTH_SHORT)
						.show();
			}
			JSONObject object;
			try {
				object = new JSONObject(s);
				JSONObject object1 = object.getJSONArray("HeWeather6")
						.getJSONObject(0);
				JSONObject pm25Obj = object1.getJSONObject("air_now_city");
				String pm25 = pm25Obj.getString("pm25");
				tv_now_pm2_5.setText("實時pm2.5:" + pm25);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <!-- 實時的天氣。整個長:1280,整個寬:480,上面選單欄:55 -->

    <EditText
        android:id="@+id/main_editView"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="請輸入城市名稱" />

    <Button
        android:id="@+id/main_button"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="查詢" />

    <TextView
        android:id="@+id/tv_now_temperature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:textColor="@color/white"
        android:textSize="@dimen/normalSize" />

    <TextView
        android:id="@+id/tv_now_weatherName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textColor="@color/white"
        android:textSize="@dimen/normalSize" />

    <TextView
        android:id="@+id/tv_now_pm2_5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textColor="@color/white"
        android:textSize="@dimen/normalSize" />

    <!-- 今明後天的天氣 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <!-- 今天的天氣 -->

        <LinearLayout
            android:id="@+id/today_weather_ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <!-- 最上面的日期 -->

            <TextView
                android:id="@+id/tv_today_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_today_temperature"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_today_weatherName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_today_PM2_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize"
                android:visibility="gone" />
        </LinearLayout>

        <!-- 明天的天氣 -->

        <LinearLayout
            android:id="@+id/tomorrow_weather_ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv_tomorrow_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_tomorrow_temperature"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_tomorrow_weatherName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_tomorrow_PM2_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize"
                android:visibility="gone" />
        </LinearLayout>

        <!-- 後天的天氣 -->

        <LinearLayout
            android:id="@+id/dayaftertomorrow_weather_ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv_dayaftertomorrow_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_dayaftertomorrow_temperature"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_dayaftertomorrow_weatherName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize" />

            <TextView
                android:id="@+id/tv_dayaftertomorrow_PM2_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:textColor="@color/white"
                android:textSize="@dimen/normalSize"
                android:visibility="gone" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>