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

Android 網路請求之 GET:用 HttpURLConnection 實作並回傳 UI

編輯:關於 Android 開發

在引入任何第三方框架之前,先直接用 SDK 內建的 HttpURLConnection 走一次 GET,有助於理解後續 Volley、Retrofit 到底替你做了什麼。

整段流程可以拆成五步:開連線 → 設定逾時與標頭 → 檢查回應碼 → 讀取串流並組字串 → 透過 Handler 把結果送回主線程更新 UI。

package com.jredu.helloworld.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import com.jredu.helloworld.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUrlConnectionGetActivity extends AppCompatActivity {
    WebView webView;
    Button button;
    TextView success;

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

        webView = (WebView) findViewById(R.id.baidu);
        success = (TextView) findViewById(R.id.success);
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 網路操作必須放在子執行緒,否則會觸發
                // NetworkOnMainThreadException
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpUrlConnectionGet();
                    }
                }).start();
            }
        });
    }

    public void HttpUrlConnectionGet() {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL("https://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(5 * 1000);   // 連線逾時
            urlConnection.setReadTimeout(5 * 1000);      // 讀取逾時
            urlConnection.setRequestProperty("apikey",
                    "fc642e216cd19906f642ee930ce28174"); // 自訂請求標頭
            urlConnection.connect();

            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = urlConnection.getInputStream();
                byte[] bytes = new byte[1024];
                int i = 0;
                while ((i = is.read(bytes)) != -1) {
                    sb.append(new String(bytes, 0, i, "utf-8"));
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        // 把結果交給主線程
        Message message = handler.obtainMessage(1, sb.toString());
        handler.sendMessage(message);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 1) {
                String s = (String) msg.obj;
                webView.getSettings().setDefaultTextEncodingName("utf-8");
                webView.getSettings().setJavaScriptEnabled(true);
                webView.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
            }
        }
    };
}

幾個關鍵細節

一定要放在子執行緒。從 Android 4.0 起,主線程禁止執行網路 I/O,否則直接拋 NetworkOnMainThreadException。

逾時要主動設定。預設值可能長到讓使用者以為 App 當機,連線與讀取逾時建議都設在數秒內。

串流要在 finally 中收尾。InputStream 與 HttpURLConnection 都應該確實關閉,否則在頻繁請求時容易耗盡連線。實務上更推薦用 try-with-resources 自動關閉。

別忘了網路權限。AndroidManifest.xml 中需要 <uses-permission android:name="android.permission.INTERNET" />。

為什麼用 Handler 而不是 runOnUiThread?兩者都能回到主線程,但 Handler 的訊息模型更適合有多種請求類型、需要依 what 分派的情境,也更容易在 Activity 銷毀時統一 removeMessages() 清理。

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