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

Android 通過 GET 與 POST 提交參數給 Web 應用的完整實踐

編輯:關於 Android 程式設計

本文示範如何把 Android 端的表單數據上傳到後端 Web 應用。場景很簡單:界面有「視頻名稱」與「時長」兩個輸入框,點擊保存按鈕提交,服務端用 ManageServlet 接收。

一、GET 方式

服務端

public class ManageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        String title = request.getParameter("title");
        // Tomcat 預設以 ISO8859-1 解碼,需手動轉回 UTF-8
        title = new String(title.getBytes("ISO8859-1"), "UTF-8");
        String timelength = request.getParameter("timelength");
        System.out.println("視頻名稱:" + title);
        System.out.println("時長:" + timelength);
    }
}

Android 端

public class MainActivity extends Activity {
    private EditText titleText;
    private EditText lengthText;

    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.main);

        titleText = (EditText) this.findViewById(R.id.title);
        lengthText = (EditText) this.findViewById(R.id.timelength);
        Button saveButton = (Button) this.findViewById(R.id.button);
        saveButton.setOnClickListener(new ButtonClickListener());
    }

    private static class ButtonClickListener implements View.OnClickListener {
        public void onClick(View v) {
            String title = titleText.getText().toString();
            String length = lengthText.getText().toString();
            boolean result = NewsService.save(title, length);
            Toast.makeText(getApplicationContext(),
                    result ? R.string.success : R.string.error, 1).show();
        }
    }
}

網絡層

HTTP 協議中,GET 與 POST 都能提交參數。一般經驗法則是:2K 以內的數據兩者皆可,超過 2K 必須用 POST。GET 的特點是把參數拼在 URL 後面。

public class NewsService {
    public static boolean save(String title, String length) {
        String path = "https://192.168.1.100:8080/web/ManageServlet";
        Map<String, String> params = new HashMap<String, String>();
        params.put("title", title);
        params.put("timelength", length);
        try {
            return sendGETRequest(path, params, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /* 拼接 GET 請求 */
    private static boolean sendGETRequest(String path,
                                          Map<String, String> params,
                                          String encoding) throws Exception {
        // 最終形如:...ManageServlet?title=xxx&timelength=90
        StringBuilder url = new StringBuilder(path);
        url.append("?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));
            url.append("&");
        }
        url.deleteCharAt(url.length() - 1);

        HttpURLConnection conn =
                (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        return conn.getResponseCode() == 200;
    }
}

二、中文亂碼從何而來

亂碼通常有兩個獨立成因,需要分別處理:

  1. 客戶端沒做 URL 編碼。中文直接拼進 URL 會被截斷或錯解,必須用 URLEncoder.encode(value, "UTF-8")。
  2. Tomcat 預設以 ISO8859-1 解析參數。此時服務端要還原:new String(title.getBytes("ISO8859-1"), "UTF-8")。

用 Filter 統一處理編碼

參數一多,每個都手動轉碼既麻煩又易漏。更優雅的做法是寫一個 Filter,攔截所有請求統一處理。

public class EncodingFilter implements Filter {

    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if ("GET".equals(req.getMethod())) {
            // GET 參數來自 URL,需要包裝後重新解碼
            chain.doFilter(new EncodingHttpServletRequest(req), response);
        } else {
            req.setCharacterEncoding("UTF-8");
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException { }
}

搭配的請求包裝類:

public class EncodingHttpServletRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public EncodingHttpServletRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {
        String value = request.getParameter(name);
        if (value != null) {
            try {
                value = new String(value.getBytes("ISO8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) { }
        }
        return value;
    }
}

在 web.xml 中把 URL Pattern 設為 /*,之後 Servlet 裡拿到的就都是正確的 UTF-8 字符串了。

三、POST 方式

先看一次真實的 POST 報文結構:

POST /web/ManageServlet HTTP/1.1          // 方法 / 路徑 / 協議版本
Accept: */*                              // 可接收的數據類型
Referer: https://192.168.1.100:8080/web/index.jsp   // 來源路徑
User-Agent: ...                          // 客戶端標識
Content-Type: application/x-www-form-urlencoded    // 提交數據的類型
Host: 192.168.1.100:8080
Content-Length: 26                       // 數據總長度
Connection: Keep-Alive

title=liming&timelength=90               // 實體正文

關鍵點在於:GET 把參數放 URL,POST 把參數放實體正文(body)。因此 POST 不受 URL 長度限制,也更適合傳遞較大或較敏感數據。

用 HttpURLConnection 實現 POST

private static boolean sendPOSTRequest(String path,
                                       Map<String, String> params,
                                       String encoding) throws Exception {
    StringBuilder data = new StringBuilder();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            data.append(entry.getKey()).append("=");
            data.append(URLEncoder.encode(entry.getValue(), encoding));
            data.append("&");
        }
        data.deleteCharAt(data.length() - 1);
    }

    byte[] entity = data.toString().getBytes();

    HttpURLConnection conn =
            (HttpURLConnection) new URL(path).openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);                 // 允許向服務端寫數據
    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length",
                            String.valueOf(entity.length));

    OutputStream out = conn.getOutputStream();
    out.write(entity);
    // 注意:此時數據只寫入本地緩衝,需讀取響應碼後才真正送出
    return conn.getResponseCode() == 200;
}

四、更省事的方案:HttpClient

HttpClient 封裝了連接池、重試、Cookie 等細節,能勝任瀏覽器的大部分工作,代碼量顯著減少。

private static boolean sendHttpClientPOSTRequest(String path,
                                                 Map<String, String> params,
                                                 String encoding)
                                                 throws Exception {
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);
    HttpPost httpPost = new HttpPost(path);
    httpPost.setEntity(entity);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);
    return response.getStatusLine().getStatusCode() == 200;
}

五、該選哪一個

HttpURLConnection 是官方推薦的原生方案,實現透明、無需額外依賴,但連接管理要自己操心。HttpClient 功能強大但已於 API 22 被標記為 deprecated。如今的標準答案是 OkHttp 或 Retrofit:前者提供簡潔的同步/異步 API 與連接複用,後者則能用註解把接口聲明式地描述出來,並自動完成 JSON 序列化。本文的兩種寫法適合作為理解 HTTP 底層原理的入門,實際專案建議直接採用現代化框架。

另外别忘了:無論用哪種方式,網絡請求都必須放在子線程,並在 manifest 中申請 android.permission.INTERNET 權限。

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