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

Android 實作:用百度 APIstore 與 JSON 抓取新聞頻道與內容

編輯:關於 Android 程式設計

本文示範一個完整的流程:呼叫百度 APIstore 的新聞介面取得頻道清單,用 Spinner 呈現;使用者挑選頻道後,再請求該頻道的新聞列表並顯示出來。整份程式拆成三個工具類加上兩個 Activity。

一、檔案工具類 FileUitlity

負責決定快取目錄位置(有 SD 卡就用 SD 卡,沒有就退回 app 內部目錄),並提供寫檔方法。這裡用了單例模式:

public class FileUitlity {
    private static String ROOT_CACHE;
    private static FileUitlity instance = null;

    private FileUitlity() { }

    public static FileUitlity getInstance(Context context, String root_dir) {
        if (instance == null) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                ROOT_CACHE = Environment.getExternalStorageDirectory() + "/" + root_dir + "/";
            } else {
                ROOT_CACHE = context.getFilesDir().getAbsolutePath() + "/" + root_dir + "/";
            }
            File dir = new File(ROOT_CACHE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            instance = new FileUitlity();
        }
        return instance;
    }

    public static String saveFileToSdcard(String fileName, String content) {
        String state = Environment.getExternalStorageState();
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            return "SD 卡未就緒";
        }
        File root = Environment.getExternalStorageDirectory();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(root + "/" + fileName);
            fos.write(content.getBytes());
            return "ok";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try { fos.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
        return "";
    }
}

二、網路請求工具類 HttpUtil

用 HttpURLConnection 做 GET,記得在 Request Header 帶上 apikey,並設定連線與讀取逾時:

public class HttpUtil {
    public static String HttpGet(String uri) {
        HttpURLConnection con = null;
        InputStream is = null;
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(uri);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("apikey", "你的 apikey");
            con.setConnectTimeout(5 * 1000);
            con.setReadTimeout(5 * 1000);
            // 200 成功、404 未找到、500 伺服器錯誤
            if (con.getResponseCode() == 200) {
                is = con.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
            if (con != null) {
                con.disconnect();
            }
        }
        return result;
    }
}

三、網址常數 UrlUtil

把介面位置集中管理,日後要換環境只改一處:

public class UrlUtil {
    // 取得新聞頻道清單
    public static String channelUrl =
        "https://apis.baidu.com/showapi_open_bus/channel_news/channel_news";

    /* 取得頻道對應的新聞,GET 參數:
       channelId   新聞頻道 id,必須精確匹配
       channelName 頻道名稱,可模糊匹配
       title       新聞標題,可模糊匹配
       page        頁數,預設 1,每頁最多 20 條
       needContent 是否回傳正文,1 為需要
       needHtml    是否回傳正文 HTML,1 為需要 */
    public static String newsUrl =
        "https://apis.baidu.com/showapi_open_bus/channel_news/search_news";
}

四、主畫面:頻道選取與新聞顯示

版面很簡單,一個 Spinner 加一個可捲動的 TextView:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Spinner
        android:id="@+id/channe1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/channe1">

        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</RelativeLayout>

先用 AsyncTask 抓頻道清單餵給 SimpleAdapter,並在 Spinner 的選取事件中帶著 channelId 去抓新聞:

public class HttpJsonActivity extends AppCompatActivity {
    private TextView tv;
    private Spinner channe1;
    private SimpleAdapter sa;
    private List<Map<String, String>> channe1List;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_json);
        tv = (TextView) findViewById(R.id.tv);
        channe1 = (Spinner) findViewById(R.id.channe1);
        channe1List = new ArrayList<>();

        sa = new SimpleAdapter(this, channe1List,
                android.R.layout.simple_spinner_item,
                new String[]{"name"},
                new int[]{android.R.id.text1});
        channe1.setAdapter(sa);

        new GetChanel().execute();

        channe1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> map = channe1List.get(position);
                String channelName = map.get("name");
                String channelId = map.get("channelId");
                String url = UrlUtil.newsUrl + "?channelId=" + channelId
                        + "&channelName=" + channelName
                        + "&needContent=1&needHtml=1";
                new GetNew().execute(url);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
    }

    // 抓取頻道清單
    public class GetChanel extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            return HttpUtil.HttpGet(UrlUtil.channelUrl);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("")) {
                Toast.makeText(getBaseContext(), "沒有資料", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject obj = new JSONObject(s);
                JSONObject body = obj.getJSONObject("showapi_res_body");
                JSONArray ja = body.getJSONArray("channelList");
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject channelObj = (JSONObject) ja.get(i);
                    Map<String, String> map = new HashMap<>();
                    map.put("channelId", channelObj.getString("channelId"));
                    map.put("name", channelObj.getString("name"));
                    channe1List.add(map);
                }
                sa.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    // 抓取指定頻道的新聞
    public class GetNew extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.HttpGet(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tv.setText(s.equals("") ? "沒有資料" : s);
        }
    }
}

實際執行的畫面:

五、額外:把回傳結果存成檔案

另一個 Activity 示範如何把抓回來的 JSON 直接寫進 SD 卡,方便離線除錯:

public class APIActivity extends AppCompatActivity {
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_api);
        tv = (TextView) findViewById(R.id.tv);
        new MyGetJson().execute(UrlUtil.channelUrl);
    }

    public class MyGetJson extends AsyncTask<String, Void, String> {
        // doInBackground 在子執行緒執行,onPostExecute 回到主執行緒
        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.HttpGet(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tv.setText(s);
            saveFile(s);
        }
    }

    public void saveFile(String s) {
        Toast.makeText(this, FileUitlity.saveFileToSdcard("abcdef.txt", s),
                Toast.LENGTH_SHORT).show();
    }
}

六、實務提醒

原始範例把 apikey 直接寫在原始碼裡,這在正式專案中並不合適,應該移到 build 設定或伺服端代理。另外,TargetSdk 在 Android 10 以上已不允許直接寫入外部儲存空間根目錄,需要改用 app 專屬目錄或 MediaStore。原範例在解析 channelId 時誤用了 channelName 當 key,這裡已一併修正。

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