Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 向中國天氣網發送 GET 請求獲取 JSON 資料實例

編輯:關於 Android 程式設計

本實例示範如何向中國天氣網發送 GET 請求、獲取 JSON 資料並解析顯示。

網路工具類

package com.android.xiong.jsontest;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttUtil {
    // 創建 HttpClient 物件
    public static HttpClient httpClient = new DefaultHttpClient();

    /**
     * @param url 請求地址
     * @return 伺服器響應的字串
     */
    public static String getRequest(final String url) throws InterruptedException, ExecutionException {
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                HttpGet get = new HttpGet(url);            // 創建 HttpGet 物件
                HttpResponse httpResponse = httpClient.execute(get); // 發送 get 請求
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    // 獲取伺服器響應的字串
                    return EntityUtils.toString(httpResponse.getEntity());
                }
                return null;
            }
        });
        new Thread(task).start();
        return task.get();
    }
}

主介面

透過子執行緒發送請求,並以廣播接收器接收返回的資料後解析 JSON 顯示:

package com.android.xiong.jsontest;

import java.util.concurrent.ExecutionException;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;

public class ActivityMian extends Activity {
    public final static String RECI_COAST = com.android.xiong.HTTUTIL;
    TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mian);
        show = (TextView) findViewById(R.id.show);
        // 注冊廣播
        IntentFilter filter = new IntentFilter(RECI_COAST);
        BroadcastReceiver myrecive = new MyRecive();
        registerReceiver(myrecive, filter);
        new Thread() {
            @Override
            public void run() {
                Intent intent = new Intent(RECI_COAST);
                try {
                    // 獲取伺服器返回的資訊
                    String reslut = HttUtil.getRequest("https://m.weather.com.cn/data/101020100.html");
                    intent.putExtra("weatherinfo", reslut);
                    sendBroadcast(intent); // 發送廣播
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // 定義 BroadcastReceiver 接收返回的資訊
    private class MyRecive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                // 獲取 JSONObject 物件
                JSONObject jsonobject = new JSONObject(intent.getStringExtra("weatherinfo"));
                JSONObject jsoncity = new JSONObject(jsonobject.getString("weatherinfo"));
                show.setText("城市:" + jsoncity.getString("city") + " 日期:"
                        + jsoncity.getString("date_y") + " 今天天氣:"
                        + jsoncity.getString("temp1") + jsoncity.getString("weather1")
                        + jsoncity.getString("wind1"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_mian, menu);
        return true;
    }
}

透過 FutureTask 封裝 GET 請求,在子執行緒中取得天氣網返回的 JSON,再以廣播機制將資料傳回主執行緒解析並顯示城市、日期與天氣資訊。

轉載請注明出處:https://blog.csdn.net/x605940745

源代碼下載地址:https://download.csdn.net/detail/x605940745/6739893

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved