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

Android 使用 GET / POST 存取 HTTP 伺服器完整實作

編輯:關於 Android 程式設計

曾經我覺得 Android 的網路通訊有點神奇,直到把網路基礎補起來,才發現一切都很有條理。這篇就透過一個小 Demo,把 GET 與 POST 兩種提交方式講清楚。

Demo 要做什麼

1. 用戶端可以抓取一個網頁的內容;
2. 用戶端把使用者名稱與密碼提交到 HTTP 伺服器,並在 Tomcat 主控台看到收到的內容。

一、抓取網頁內容

package com.hwb.service;

import java.net.HttpURLConnection;
import java.net.URL;

public class HtmlContentService {
    /**
     * 依路徑取得資料
     */
    public static byte[] getContent(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setReadTimeout(5000);
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] arr = new byte[1024];
            int res = -1;
            while ((res = in.read(arr)) != -1) {
                byteArrayOutputStream.write(arr, 0, res);
            }
            byteArrayOutputStream.close();
            in.close();
            return byteArrayOutputStream.toByteArray();
        }
        return null;
    }
}

這個方法就能完成一次完整的 HTTP 請求。回應先讀成位元組陣列,後續要怎麼處理都很自由——例如直接取得某個網站的原始碼。實務上更常見的是伺服器回傳 XML 或 JSON 字串,同樣先收為二進位資料,再交給解析器處理即可。

二、伺服器端:一個簡單的 Servlet

package com.hwb.control;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class UserServlet extends HttpServlet {
    /** 接收兩個參數並在主控台印出 */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println("name =" + name + ",password = " + password);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

三、用戶端:GET 與 POST 兩種提交

package com.hwb.service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class UserService {

    /** 以 GET 方式提交資料 */
    public static boolean sendDataByGet(String path, String userName, String passWord) {
        try {
            StringBuilder stringBuilder = new StringBuilder(path);
            stringBuilder.append("?name=")
                    .append(URLEncoder.encode(userName, "UTF-8"))
                    .append("&password=")
                    .append(URLEncoder.encode(passWord, "UTF-8"));
            URL url = new URL(stringBuilder.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /** 以 POST 方式提交資料 */
    public static boolean sendDataByPost(String path, String userName, String passWord) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            StringBuilder builder = new StringBuilder();
            builder.append("name=").append(URLEncoder.encode(userName, "UTF-8"))
                   .append("&password=").append(URLEncoder.encode(passWord, "UTF-8"));
            byte[] arr = builder.toString().getBytes();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(arr.length));
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(arr);
            if (conn.getResponseCode() == 200) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

四、GET 與 POST 的差別

用攔截工具比對兩次請求,差異一目了然:

GET 把參數接在網址後面,POST 則把參數放進請求本體。這帶來兩個實際影響:GET 的長度受網址限制、參數會暴露在網址列與伺服器日誌中;POST 則可承載更大的資料量,也不適合被瀏覽器快取或加入書籤。

五、中文亂碼怎麼辦

先看 GET 的情況:

再看 POST:

很明顯,兩者都出現了亂碼。原因在於 Tomcat 預設以 ISO-8859-1 解碼請求參數。

POST 的處理相對簡單,只要明確指定編碼即可:

httpServletRequest.setCharacterEncoding("UTF-8");

GET 比較麻煩,因為編碼發生在 URI 解析階段,此時 setCharacterEncoding() 已經來不及了。常見做法是自訂一個 Filter,包裝 request 並在 getParameter() 時做一次編碼轉換:

String value = super.getParameter(name);
return new String(value.getBytes("ISO-8859-1"), "UTF-8");

完整實作如下:

package com.hwb.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter {
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) arg0;
        HttpServletResponse httpServletResponse = (HttpServletResponse) arg1;
        String method = httpServletRequest.getMethod();
        if (method.equals("GET")) {
            EncodingWrap encodingWrap = new EncodingWrap(httpServletRequest);
            arg2.doFilter(encodingWrap, httpServletResponse);
        } else if (method.equals("POST")) {
            httpServletRequest.setCharacterEncoding("UTF-8");
            arg2.doFilter(httpServletRequest, httpServletResponse);
        }
    }
}
package com.hwb.filter;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EncodingWrap extends HttpServletRequestWrapper {
    public EncodingWrap(HttpServletRequest request) {
        super(request);
    }

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

以上大致就是完整流程。若有理解不到位之處,歡迎指正。

補充一點:如果是上傳檔案,建議改用 Socket 或 multipart 串流處理。HTTP 伺服器對單次請求的資料量通常設有上限,直接塞大檔案進表單很容易失敗。

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