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

Android 以 GET 方式提交資料到伺服器:HttpURLConnection 完整實作

編輯:關於 Android 開發

Android 以 GET 方式提交資料到伺服器:HttpURLConnection 完整實作

行動應用幾乎都要跟後端打交道。本文從零開始搭建一個最簡單的登入場景:先用 Servlet 模擬伺服器端,再用 Android 客戶端以 GET 方式把帳號密碼送過去,並處理回應。

一、伺服器端:LoginServlet

新建動態 Web 專案,撰寫 Servlet:

package com.wuyudong.web;

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;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用戶名:" + username);
        System.out.println("密碼:" + password);

        if ("wuyudong".equals(username) && "123".equals(password)) {
            response.getOutputStream().write("login success".getBytes());
        } else {
            response.getOutputStream().write("login failed".getBytes());
        }
    }

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

再補一個 JSP 頁面方便用瀏覽器自測:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登錄頁面</title>
</head>
<body>
<form action="LoginServlet" method="get">
 用戶名:<input name="username" type="text"><br>
 密碼:<input name="password" type="password"><br>
 <input type="submit">
</form>
</body>
</html>

二、客戶端版面配置

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

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

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

    <Button android:onClick="login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登錄" />
</LinearLayout>

三、送出請求

package com.wuyudong.loginclient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

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

public class MainActivity extends Activity {
    private EditText et_name;
    private EditText et_pwd;

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

    public void login(View view) {
        String name = et_name.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "用戶名密碼不能為空", 0).show();
        } else {
            // 模擬 http 請求,提交數據到服務器
            String path = "https://169.254.168.71:8080/web/LoginServlet?username="
                    + name + "&password=" + pwd;
            try {
                URL url = new URL(path);
                // 建立一個 http 連接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 設置請求方式,注意 GET 字母一定要大寫
                conn.setRequestMethod("GET");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
                        + "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

                int code = conn.getResponseCode(); // 200 OK / 404 / 503
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    // 把 is 的內容轉換為字符串
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                    }
                    String result = new String(bos.toByteArray());
                    is.close();
                    Toast.makeText(this, result, 0).show();
                } else {
                    Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "請求失敗,請檢查 logcat 日誌控制台", 0).show();
            }
        }
    }
}

別忘了在 AndroidManifest.xml 加上網路權限:

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

四、踩到的坑:NetworkOnMainThreadException

直接執行,點下按鈕後會看到這樣的錯誤:

android.os.NetworkOnMainThreadException

從 Android 3.0(Honeycomb)開始,系統禁止在主執行緒(UI Thread)進行網路 I/O,以避免畫面卡頓甚至 ANR。快速繞過的方式是在 onCreate() 中放寬政策:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

但這只是讓程式跑得起來,並不是好做法。正式專案應該把網路請求放進 AsyncTask、Thread、Kotlin 協程或 RxJava 等工作執行緒,透過 Handler 或相應機制回主執行緒更新 UI。

五、GET 的先天限制

參數直接拼在網址後面,意味著:中文與特殊字元必須先做 URL Encode;長度受伺服器與代理的限制;最關鍵的是密碼會明文出現在網址與伺服器存取日誌中。所以登入這類敏感操作,實務上都應該改用 POST 並全程走 HTTPS。下一篇我們就把 POST 版本做出來做對照。

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