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

Android 網絡編程:用 POST 把數據送到伺服器(二)

編輯:關於 Android 程式設計

上一篇談的是 GET 方式傳遞數據,適用於資料量不超過 2KB、對安全性要求不高的場景。本篇接著說明 POST 方式。

POST 是 Android 應用提交數據給伺服器的主要手段,適合資料量大、型別複雜、安全性要求高的場合。

一、建立伺服器端

專案結構如下:

第一步:撰寫控制器 Servlet

package com.jph.sp.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ServletForPOSTMethod")
public class ServletForPOSTMethod extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        System.out.println("name from POST method: " + name);
        System.out.println("pwd from POST method: " + pwd);
    }
}

伺服器端到此完成,接著建立 Android 端。

二、建立 Android 端

專案結構如下:

第一步:業務邏輯層 SendDateToServer.java

package com.jph.sp.service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import android.os.Handler;

/**
 * 以 POST 方式向伺服器發送數據
 */
public class SendDateToServer {

    private static String url =
        "https://10.219.61.117:8080/ServerForPOSTMethod/ServletForPOSTMethod";

    public static final int SEND_SUCCESS = 0x123;
    public static final int SEND_FAIL = 0x124;

    private Handler handler;

    public SendDateToServer(Handler handler) {
        this.handler = handler;
    }

    public void SendDataToServer(String name, String pwd) {
        final Map<String, String> map = new HashMap<String, String>();
        map.put("name", name);
        map.put("pwd", pwd);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (sendPostRequest(map, url, "utf-8")) {
                        // 通知主線程:發送成功
                        handler.sendEmptyMessage(SEND_SUCCESS);
                    } else {
                        // 發送失敗的處理
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private boolean sendPostRequest(Map<String, String> param, String url, String encoding)
            throws Exception {
        // 組出帶參數的請求位址
        StringBuffer sb = new StringBuffer(url);
        if (!url.equals("") && !param.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : param.entrySet()) {
                sb.append(entry.getKey() + "=");
                sb.append(URLEncoder.encode(entry.getValue(), encoding));
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1); // 移除最後一個 &
        }
        byte[] data = sb.toString().getBytes();

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");            // 請求方式設為 POST
        conn.setDoOutput(true);                   // 允許對外傳輸數據
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", data.length + "");

        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(data);
        outputStream.flush();

        if (conn.getResponseCode() == 200) {
            return true;
        }
        return false;
    }
}

第二步:撰寫 Activity

package com.jph.sp.activity;

import com.jph.sp.service.SendDateToServer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText edtName, edtPwd;
    private Button btnSend;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SendDateToServer.SEND_SUCCESS:
                    Toast.makeText(MainActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();
                    break;
                case SendDateToServer.SEND_FAIL:
                    Toast.makeText(MainActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edtName = (EditText) findViewById(R.id.edtName);
        edtPwd = (EditText) findViewById(R.id.edtPwd);
        btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = edtName.getText().toString();
                String pwd = edtPwd.getText().toString();
                if (name.equals("") || pwd.equals("")) {
                    Toast.makeText(MainActivity.this, "用戶名或密碼不能為空",
                            Toast.LENGTH_LONG).show();
                } else {
                    new SendDateToServer(handler).SendDataToServer(name, pwd);
                }
            }
        });
    }
}

Android 端完成,來看實際運行結果:

小結

POST 與 GET 的關鍵差異在於:POST 把參數寫進輸出串流、並需要設定 Content-Type 與 Content-Length;兩者都必須放在子執行緒中執行,再用 Handler 回主線程更新 UI,這是 Android 網路請求的基本紀律。

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