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

Android HTTP 請求實作:發送 GET、接收回應並在畫面上呈現

編輯:關於 Android 程式設計

所有需要跟後端打交道的 App,第一步都是「送出請求、拿到回應」。這個範例用最經典的 Apache HttpClient 走一遍,把結果直接顯示在 WebView 上,方便驗證字串是否正確。

步驟一:權限

網路權限必須先宣告,否則會拿到 Permission denied:

<uses-permission android:name="android.permission.INTERNET" />

步驟二:完整的 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.httpdemo1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.example.httpdemo1.HttpDemo1Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

步驟三:版面配置

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

    <TextView
        android:id="@+id/myWebTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/requestBtn"
        android:layout_below="@id/myWebTitle" />

    <Button
        android:id="@+id/requestBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Send Request" />

</RelativeLayout>

步驟四:送出請求並處理回應

package com.example.httpdemo1;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
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 android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

public class HttpDemo1Activity extends Activity {

    private Button mSendReqBtn = null;
    private WebView mWebView = null;
    private HttpResponse mHttpResponse = null;
    private HttpEntity mHttpEntity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_demo1);
        mSendReqBtn = (Button) findViewById(R.id.requestBtn);
        mSendReqBtn.setOnClickListener(mSendClickListener);
        mWebView = (WebView) findViewById(R.id.webview);
    }

    private OnClickListener mSendClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // 建立請求物件與 HTTP 客戶端
            HttpGet httpGet = new HttpGet("https://www.baidu.com/");
            HttpClient httpClient = new DefaultHttpClient();

            InputStream inputStream = null;
            try {
                // 送出請求並取得回應
                mHttpResponse = httpClient.execute(httpGet);
                mHttpEntity = mHttpResponse.getEntity();
                inputStream = mHttpEntity.getContent();

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String result = "";
                String line = "";
                while (null != (line = bufferedReader.readLine())) {
                    result += line;
                }
                System.out.println(result);   // 可在 LogCat 查看

                // 把 HTML 字串直接載入 WebView 顯示
                mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
                // 直接 loadData 會顯示找不到網頁,改用下面這個版本才正常
                mWebView.loadDataWithBaseURL(null, result, "text/html", "utf-8", null);
                // mWebView.loadUrl("https://www.baidu.com/");  // 直接載入 URL 也行
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

執行結果如下:

幾點必要的現代化提醒

這份程式碼有幾處在今天不能直接照抄。第一,DefaultHttpClient 所屬的 Apache HTTP Client 已在 Android 5.1 標記為 deprecated,並從 Android 6.0 起被移除,現在請改用 HttpURLConnection 或 OkHttp。第二,網路操作必須放在背景執行緒,範例直接寫在 onClick 裡會觸發 NetworkOnMainThreadException,正式做法是用非同步任務、Thread 加 Handler,或 Kotlin 的協程。

第三,loadDataWithBaseURL() 之所以比 loadData() 好用,是因為前者能正確處理含 #、% 等特殊字元的 HTML,後者會解析失敗而顯示「找不到網頁」。第四,while 迴圈用 result += line 累加字串,每次迴圈都會產生新的字串物件,改用 StringBuilder 會省下可觀的配置。這些細節,正好都是從「能跑」到「跑得好」的距離。

參考資料:Android Reference — package org.apache.http
https://developer.android.com/reference/org/apache/http/package-summary.html

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