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

Android HTTP 同步請求實作:GET、POST 與 HttpClient 的四種寫法

編輯:關於 Android 開發

Android HTTP 同步請求實作

這篇把最基礎的四種 HTTP 請求寫法放在一起對照:HttpURLConnection 的 GET 與 POST,以及 HttpClient 的 GET 與 POST。同一件事寫四遍,差異就很清楚了。

1. 介面

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

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名"
        android:text="張三" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <Button
        android:onClick="myGetData"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陸" />
</LinearLayout>

2. MainActivity:回應按鈕點擊

重點在於網路請求必須放在子執行緒,完成後再切回主執行緒更新 UI:

package com.example.getdata;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et_username;
    private EditText et_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
    }

    public void myGetData(View view) {
        final String username = et_username.getText().toString().trim();
        final String password = et_password.getText().toString().trim();
        System.out.println("username:" + username);
        System.out.println("password:" + password);

        new Thread() {
            public void run() {
                // 四種寫法擇一,切換註解即可對照
                // final String result = LoginService.loginByGet(username, password);
                // final String result = LoginService.loginByPost(username, password);
                // final String result = LoginService.loginByClientGet(username, password);
                final String result = LoginService.loginByClientPost(username, password);

                if (result != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, result, 0).show();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "請求不成功!", 0).show();
                        }
                    });
                }
            }
        }.start();
    }
}

3. LoginService:四種請求寫法

package com.example.getdata.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

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

import com.example.getdata.utils.StreamTools;

/* 注意事項:送出請求時若含有中文,記得轉成對應編碼 */
public class LoginService {

    /** 寫法一:HttpURLConnection + GET */
    public static String loginByGet(String username, String password) {
        try {
            String path = "https://192.168.1.100/android/index.php?username="
                    + URLEncoder.encode(username, "utf-8")
                    + "&password=" + password;
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                return StreamTools.readInputStream(is);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 寫法二:HttpURLConnection + POST */
    public static String loginByPost(String username, String password) {
        String path = "https://192.168.1.101/android/index.php";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            String data = "username=" + URLEncoder.encode(username, "utf-8")
                    + "&password=" + password;
            conn.setRequestProperty("Content-Length", data.length() + "");
            conn.setDoOutput(true);                 // 允許對外寫入資料
            OutputStream os = conn.getOutputStream();
            os.write(data.getBytes());

            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                return StreamTools.readInputStream(is);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 寫法三:HttpClient + GET */
    public static String loginByClientGet(String username, String password) {
        try {
            HttpClient client = new DefaultHttpClient();   // 開一個「瀏覽器」
            String path = "https://192.168.1.101/android/index.php?username="
                    + URLEncoder.encode(username, "utf-8")
                    + "&password=" + password;
            HttpGet httpGet = new HttpGet(path);

            HttpResponse response = client.execute(httpGet);   // 按下 Enter
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                InputStream is = response.getEntity().getContent();
                return StreamTools.readInputStream(is);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 寫法四:HttpClient + POST */
    public static String loginByClientPost(String username, String password) {
        try {
            HttpClient client = new DefaultHttpClient();
            String path = "https://192.168.1.101/android/index.php";
            HttpPost httpPost = new HttpPost(path);

            // 組裝要提交的參數
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("username", username));
            parameters.add(new BasicNameValuePair("password", password));

            httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
            HttpResponse response = client.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                InputStream is = response.getEntity().getContent();
                return StreamTools.readInputStream(is);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

4. StreamTools:把輸入流轉成字串

package com.example.getdata.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {
    /** 功能:把 InputStream 轉為 String */
    public static String readInputStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] result = baos.toByteArray();
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

5. 清單檔

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

最後:關於「同步」這件事

一般來說子執行緒無法直接改動 UI,但這裡用 runOnUiThread 把 Toast 丟回主執行緒,所以能正常顯示,而不必改用 Handler 發送消息。

要注意的是,這四種寫法在「等待回應」這一步都是同步阻塞的——差別只在 API 風格。真正該記住的觀念是:無論用哪一種,都不能在主執行緒呼叫,否則在 Android 4.0 之後會直接拋出 NetworkOnMainThreadException。此外,Apache HttpClient 自 API 23 起已被移除,新專案請直接使用 HttpURLConnection,或改用 OkHttp 這類現代化的 HTTP 客戶端。

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