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

Android HTTP 網路請求實戰:GET、POST 與圖片下載完整範例

編輯:關於 Android 程式設計

本文以 HttpURLConnection 為例,示範四種最常見的 HTTP 情境:直接抓取網頁內容、以 GET 帶參數、以 POST 送出表單,以及下載並顯示網路圖片。所有範例都可在 Android 4.0 以上環境運行,並附完整的 AndroidManifest 與版面配置。

一、主畫面:四顆按鈕分派不同請求

用 Bundle 帶一個 id 跳轉到顯示頁,讓顯示頁決定要執行哪一種請求:

package com.ywhttpurlconnection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class YwhttpurlconnectionActivity extends Activity {
    private Button btn1 = null; // 直接獲取數據
    private Button btn2 = null; // GET 方式傳遞
    private Button btn3 = null; // POST 方式傳遞
    private Button btn4 = null; // 獲取圖片

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn1 = (Button) this.findViewById(R.id.Button01);
        btn2 = (Button) this.findViewById(R.id.Button02);
        btn3 = (Button) this.findViewById(R.id.Button03);
        btn4 = (Button) this.findViewById(R.id.Button04);

        btn1.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(YwhttpurlconnectionActivity.this, showdata.class);
                Bundle b = new Bundle();
                b.putInt("id", 1);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
        btn2.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(YwhttpurlconnectionActivity.this, showdata.class);
                Bundle b = new Bundle();
                b.putInt("id", 2);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
        btn3.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(YwhttpurlconnectionActivity.this, showdata.class);
                Bundle b = new Bundle();
                b.putInt("id", 3);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
        btn4.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(YwhttpurlconnectionActivity.this, showdata.class);
                Bundle b = new Bundle();
                b.putInt("id", 4);
                intent.putExtras(b);
                startActivity(intent);
            }
        });
    }
}

二、請求實作:showdata

package com.ywhttpurlconnection;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class showdata extends Activity {
    private TextView tv = null;
    private ImageView iv = null;
    private Bitmap mBitmap = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.http);
        Intent intent = this.getIntent();
        Bundle b = intent.getExtras();
        int id = b.getInt("id");
        tv = (TextView) this.findViewById(R.id.TextView_HTTP);
        iv = (ImageView) this.findViewById(R.id.ImageView01);

        if (id == 1) {
            // ===== 直接獲取數據 =====
            String httpUrl = "https://www.jb-aptech.com.cn";
            URL url = null;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (url != null) {
                try {
                    // 打開連接,此處只是創建一個實例,並沒有真正的連接
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.connect(); // 連接
                    InputStream input = urlConn.getInputStream();
                    InputStreamReader inputReader = new InputStreamReader(input);
                    BufferedReader reader = new BufferedReader(inputReader);
                    String inputLine = null;
                    StringBuffer sb = new StringBuffer();
                    while ((inputLine = reader.readLine()) != null) {
                        sb.append(inputLine).append("\n");
                    }
                    reader.close();
                    inputReader.close();
                    input.close();
                    urlConn.disconnect();
                    tv.setText(sb != null ? sb.toString() : "讀取的內容:NULL");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i("TAG", "url is null");
            }
        } else if (id == 2) {
            // ===== GET 方式傳遞參數 =====
            String httpUrl = "https://liveat.acewill.cn/liveat/?cmd=1&uid=xiaoming";
            URL url = null;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (url != null) {
                try {
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.connect();
                    InputStream input = urlConn.getInputStream();
                    InputStreamReader inputReader = new InputStreamReader(input);
                    BufferedReader reader = new BufferedReader(inputReader);
                    String inputLine = null;
                    StringBuffer sb = new StringBuffer();
                    while ((inputLine = reader.readLine()) != null) {
                        sb.append(inputLine).append("\n");
                    }
                    reader.close();
                    inputReader.close();
                    input.close();
                    urlConn.disconnect();
                    tv.setText(sb != null ? sb.toString() : "讀取的內容:NULL");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i("TAG", "url is null");
            }
        } else if (id == 3) {
            // ===== POST 方式傳遞參數 =====
            String httpUrl = "https://www.jb-aptech.com.cn";
            URL url = null;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (url != null) {
                try {
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);          // post 請求不能使用緩存
                    urlConn.setInstanceFollowRedirects(true); // 是否自動重定向
                    urlConn.connect();
                    OutputStream out = urlConn.getOutputStream();
                    DataOutputStream data = new DataOutputStream(out);
                    data.writeBytes("par=" + URLEncoder.encode("hk", "GBK"));
                    data.flush();
                    data.close();
                    out.close();
                    InputStream input = urlConn.getInputStream();
                    InputStreamReader inputReader = new InputStreamReader(input);
                    BufferedReader reader = new BufferedReader(inputReader);
                    String inputLine = null;
                    StringBuffer sb = new StringBuffer();
                    while ((inputLine = reader.readLine()) != null) {
                        sb.append(inputLine).append("\n");
                    }
                    reader.close();
                    inputReader.close();
                    input.close();
                    urlConn.disconnect();
                    tv.setText(sb != null ? sb.toString() : "讀取的內容:NULL");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i("TAG", "url is null");
            }
        } else if (id == 4) {
            // ===== 下載並顯示圖片 =====
            String httpUrl = "https://www.google.com.hk/intl/zh-CN/images/logo_cn.gif";
            URL url = null;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (url != null) {
                try {
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.connect();
                    InputStream input = urlConn.getInputStream();
                    mBitmap = BitmapFactory.decodeStream(input);
                    if (mBitmap != null) {
                        iv.setImageBitmap(mBitmap);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i("TAG", "url is null");
            }
        }
    }
}

三、AndroidManifest.xml

網路請求一定要記得加 INTERNET 權限,這是最常見的「程式碼明明沒錯卻拿不到資料」的原因:

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

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

    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" >
        <activity android:label="@string/app_name" android:name=".YwhttpurlconnectionActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".showdata"></activity>
    </application>
</manifest>

四、版面配置

http.xml(結果顯示頁):

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

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

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="172dp"
        android:layout_height="307dp" >
    </ImageView>
</LinearLayout>

main.xml(功能選單):

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button android:text="直接獲取數據" android:id="@+id/Button01"
        android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
    <Button android:text="GET方式傳遞" android:id="@+id/Button02"
        android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
    <Button android:text="POST方式傳遞" android:id="@+id/Button03"
        android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
    <Button android:text="獲取圖片" android:id="@+id/Button04"
        android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>

五、執行結果

六、這份程式碼在真實專案中該怎麼改

作為教學範例它足夠清楚,但直接搬進產品會遇到幾個問題,這裡誠實指出:

  • 不能在主執行緒做網路請求。Android 4.0 之後會拋出 NetworkOnMainThreadException。請改用 ExecutorService、Kotlin 協程,或至少把請求包在背景執行緒裡,完成後用 runOnUiThread() 更新畫面。
  • 字元編碼要對齊。POST 範例用 GBK 編碼中文,讀取時卻沒有指定 charset,容易出現亂碼。建議統一走 UTF-8,並在 InputStreamReader 明確帶上編碼名稱。
  • 字串拼接大量資料時改用 StringBuilder 串接。範例已用 StringBuffer,若回應很大,建議直接以 ByteArrayOutputStream 串流處理。
  • 連線逾時必須設定。呼叫 setConnectTimeout() 與 setReadTimeout(),否則網路異常時會無限期卡住。
  • 優先考慮成熟框架。實際專案建議使用 OkHttp 或 Retrofit,它們處理了連線池、攔截器、序列化與錯誤重試等議題;下載圖片則可直接用 Glide 或 Coil,一行就能搞定快取與生命週期管理。

理解 HttpURLConnection 的原始流程,是為了知道框架背後到底做了什麼——這樣在遇到問題時,你才判斷得出是哪一層出了差錯。

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