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

Android 網路連線實作:以 POST 方式送出表單資料並取得回應

編輯:關於 Android 程式設計

App 要跟上傳資料,最直覺的方式就是 HTTP POST。相較於把參數拼在網址後面的 GET,POST 把內容放進 request body,適合傳送較長的文字或不想暴露在網址列中的欄位。以下用 Apache HttpClient 走一遍完整流程。

實作步驟拆解

  1. 建立 HttpClient 與 HttpPost 物件,指定伺服器端點。
  2. 把要送出的欄位封裝成 NameValuePair 清單。
  3. 用 UrlEncodedFormEntity 把清單編碼成表單格式,字元集指定 UTF-8 以避免中文亂碼。
  4. 呼叫 execute() 送出請求,取得 HttpResponse。
  5. 從 HttpEntity 取得 InputStream,逐行讀成字串後顯示或解析。

版面配置

一個輸入框、一個按鈕、一個用來顯示回應的 TextView 就足夠:

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

    <EditText
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="送出" />

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java 程式碼

package com.hl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SimplePOST extends Activity {
    private TextView show;
    private EditText txt;
    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        show = (TextView) findViewById(R.id.show);
        txt = (EditText) findViewById(R.id.txt);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dopost(txt.getText().toString());
            }
        });
    }

    private void dopost(String val) {
        // 封裝要送出的欄位
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", val);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("https://mhycoe.com/test/post.php");

        // 把 Map 轉成 NameValuePair 清單
        ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        if (params != null) {
            Set<String> keys = params.keySet();
            for (Iterator<String> i = keys.iterator(); i.hasNext();) {
                String key = i.next();
                pairs.add(new BasicNameValuePair(key, params.get(key)));
            }
        }

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            InputStream content = resEntity.getContent();

            String result = convertStreamToString(content);
            show.setText(result);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

兩個一定要記得的前提

權限。在 AndroidManifest.xml 的 </manifest> 之前加上網路權限,否則會收到 SocketException: Permission denied:

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

執行緒。Android 3.0 以後不允許在主執行緒(UI Thread)進行網路 I/O,直接照上面的寫法會拋出 NetworkOnMainThreadException。實務上要把 dopost() 包進 AsyncTask、Thread 或後續的 java.util.concurrent 工具裡,取得結果後再回到主執行緒更新 TextView。此外 Apache HttpClient 在 Android 5.0 之後已被標記為 deprecated,新專案建議改用 HttpURLConnection 或 OkHttp。

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