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

Android 網絡操作實戰:GET、POST、文件上傳與 HttpClient

編輯:關於 Android 程式設計

Android 中的網絡操作與 Java SE 裡並沒有本質差別,Java 中的大量網絡代碼幾乎可以直接搬過來用。動手之前,先把幾個關鍵概念理清楚。

一、GET 與 POST 的本質差異

GET 把參數拼接到 URL 後發送,長度受限制,且參數暴露在地址欄中,安全性較差。

POST 把參數放入 HTTP 請求體,長度不受限制,參數也不會直接暴露在地址中。

關鍵的認知在於:瀏覽器提交 POST 表單時,是瀏覽器幫我們把參數編碼成了符合 HTTP 協議的請求體。也就是說:

· 瀏覽器場景:用戶操作 → 瀏覽器轉為 HTTP 協議 → 發送到服務器
· 代碼場景:用戶操作 → 我們自己編碼設置 HTTP 協議 → 發送到服務器

用 Android 寫客戶端,這一步「編碼」必須自己做。GET 只需拼接地址,POST 則要手動設置請求體以及 Content-Type、Content-Length 等請求頭。

另外,Android 自帶 Apache 的 HttpClient,相當於 web 端的瀏覽器,它封裝了大量細節,按業務需要選擇相應 API 即可。(如果在 Swing 中使用,需要額外導入 jar 包。)

我在工程裡建了一個專門處理上傳下載的工具類 HttpUtil,下面按場景逐一說明。

二、從服務器獲取二進制數據

適用於圖片、視頻等:

/**
 * 從服務器獲取二進制數據,例如圖片、視頻
 * @param serverUrl   服務器地址
 * @param newFileName 保存到本地的新文件名,例如 C://test.png
 */
public static void getByteFromServer(String serverUrl, String newFileName)
        throws Exception {
    URL url = new URL(serverUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    // android 內存有限,避免長時間保持連接
    conn.setConnectTimeout(5 * 1000);

    InputStream inStream = conn.getInputStream();
    byte[] data = readInputStream(inStream);

    File imageFile = new File(newFileName);
    FileOutputStream outStream = new FileOutputStream(imageFile);
    outStream.write(data);
    outStream.close();
}

/** 將輸入流轉為字節數組 */
public static byte[] readInputStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    inStream.close();
    return outStream.toByteArray();
}

三、獲取文本數據

html、xml、json 都適用:

/**
 * 從服務器獲取文本信息
 */
public static String getTxtFromServer(String serverUrl) throws Exception {
    URL url = new URL(serverUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5 * 1000);

    InputStream inStream = conn.getInputStream();
    byte[] data = readInputStream(inStream);
    return new String(data);
}

四、GET 方式提交參數

/**
 * GET 請求:把參數拼到地址後發送
 * @param path 服務器請求地址
 * @param params 請求參數
 * @param enc 編碼
 */
public static boolean sendGetRequest(String path,
                                     Map params, String enc)
        throws Exception {
    StringBuilder sb = new StringBuilder(path);
    // 拼成 ?username=jack&password=123456&age=23
    if (params != null && !params.isEmpty()) {
        sb.append('?');
        for (Map.Entry entry : params.entrySet()) {
            sb.append(entry.getKey()).append('=')
              .append(URLEncoder.encode(entry.getValue(), enc))
              .append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
    }
    URL url = new URL(sb.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5 * 1000);
    if (conn.getResponseCode() == 200) {
        // 請求成功,可用 getByteFromServer 拿到響應數據
        return true;
    }
    return false;
}

五、POST 方式提交表單

這裡是最容易出錯的地方。瀏覽器會自動補上的協議細節,我們得手工補齊:

/**
 * POST 表單請求
 * @param path 服務器地址
 * @param params 請求參數
 * @param enc 編碼
 */
public static boolean sendPostRequest(String path,
                                      Map params, String enc)
        throws Exception {
    // username=jack&password=123456&age=23
    StringBuilder sb = new StringBuilder();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry entry : params.entrySet()) {
            sb.append(entry.getKey()).append('=')
              .append(URLEncoder.encode(entry.getValue(), enc))
              .append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
    }
    byte[] entitydata = sb.toString().getBytes();

    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(5 * 1000);
    conn.setUseCaches(false);
    conn.setDoOutput(true);   // POST 提交必須允許輸出

    // Content-Type 與 Content-Length 是必需的,其餘可省略
    conn.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length",
            String.valueOf(entitydata.length));
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Language", "zh-CN");
    conn.setRequestProperty("Connection", "Keep-Alive");

    OutputStream outStream = conn.getOutputStream();
    outStream.write(entitydata);
    outStream.flush();
    outStream.close();

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

三個必須記住的点:setDoOutput(true)、Content-Type、Content-Length。少任何一個,服務器都會收到畸形請求。

六、POST 提交 XML

/**
 * 向服務器發送 xml 數據
 */
public static boolean sendPostXMLRequest(String path, String xml, String enc)
        throws Exception {
    byte[] data = xml.getBytes();
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(5 * 1000);
    conn.setDoOutput(true);

    conn.setRequestProperty("Content-Type", "text/xml; charset=" + enc);
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

    OutputStream outStream = conn.getOutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();

    return conn.getResponseCode() == 200;
}

七、用 HttpClient 發 GET

/**
 * 通過 HttpClient 發送 get 請求
 */
public static boolean sendGetRequestFromHttpClient(String path,
        Map params, String enc) throws Exception {
    StringBuilder sb = new StringBuilder(path);
    if (params != null && !params.isEmpty()) {
        sb.append('?');
        for (Map.Entry entry : params.entrySet()) {
            sb.append(entry.getKey()).append('=')
              .append(URLEncoder.encode(entry.getValue(), enc))
              .append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
    }
    // 相當於瀏覽器
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(sb.toString());
    HttpResponse response = httpClient.execute(get);
    if (response.getStatusLine().getStatusCode() == 200) {
        // String str = EntityUtils.toString(response.getEntity());
        // InputStream in = response.getEntity().getContent();
        return true;
    }
    return false;
}

八、用 HttpClient 發 POST

/**
 * 通過 HttpClient 發送 post 請求
 */
public static boolean sendPostRequestFromHttpClient(String path,
        Map params, String enc) throws Exception {
    List paramPairs = new ArrayList();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry entry : params.entrySet()) {
            paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    // 已編碼的實體數據
    UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);

    HttpPost post = new HttpPost(path);
    post.setEntity(entitydata);

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

對比可見,HttpClient 幫我們省掉了設置請求頭和拼實體的麻煩,代碼量明顯更少。

九、POST 上傳文件

原理不神秘:瀏覽器上傳表單時,底層會把數據組織成 multipart/form-data 格式,並用一個 boundary 分隔線切分各段。我們照著模仿即可。

先封裝一個表單文件實體:

public class FormFile {
    /* 上傳文件的數據 */
    private byte[] data;
    private InputStream inStream;
    private File file;

    /* 文件名稱 */
    private String filname;

    /* 請求參數名稱 */
    private String parameterName;

    /* 內容類型 */
    private String contentType = "application/octet-stream";

    public FormFile(String filname, byte[] data, String parameterName,
                    String contentType) {
        this.data = data;
        this.filname = filname;
        this.parameterName = parameterName;
        if (contentType != null) this.contentType = contentType;
    }

    public FormFile(String filname, File file, String parameterName,
                    String contentType) {
        this.filname = filname;
        this.parameterName = parameterName;
        this.file = file;
        try {
            this.inStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (contentType != null) this.contentType = contentType;
    }

    // getter / setter 省略
}

然後手工拼裝請求體。這個方法直接基於 Socket 寫 HTTP 協議,好處是完全可控:

/**
 * 提交包含上傳文件的表單,等同於如下 web 表單:
 * 
* * * * *
* * 注意:測試時避免使用 localhost 或 127.0.0.1,它會指向模擬器本身 */ public static boolean sendPostRequest(String path, Map params, FormFile[] files) throws Exception { final String BOUNDARY = "---------------------------7da2137580612"; final String endline = "--" + BOUNDARY + "--\r\n"; // 1. 計算文件部分數據的總長度 int fileDataLength = 0; for (FormFile uploadFile : files) { StringBuilder fileExplain = new StringBuilder(); fileExplain.append("--").append(BOUNDARY).append("\r\n"); fileExplain.append("Content-Disposition: form-data;name=\"" + uploadFile.getParameterName() + "\";filename=\"" + uploadFile.getFilname() + "\"\r\n"); fileExplain.append("Content-Type: " + uploadFile.getContentType() + "\r\n\r\n\r\n"); fileDataLength += fileExplain.length(); if (uploadFile.getInStream() != null) { fileDataLength += uploadFile.getFile().length(); } else { fileDataLength += uploadFile.getData().length; } } // 2. 構造文本類型參數的實體 StringBuilder textEntity = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { textEntity.append("--").append(BOUNDARY).append("\r\n"); textEntity.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); textEntity.append(entry.getValue()).append("\r\n"); } // 3. 計算實體總長度 int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; URL url = new URL(path); int port = url.getPort() == -1 ? 80 : url.getPort(); Socket socket = new Socket(InetAddress.getByName(url.getHost()), port); OutputStream outStream = socket.getOutputStream(); // 4. 按 HTTP 協議寫請求行與請求頭 outStream.write(("POST " + url.getPath() + " HTTP/1.1\r\n").getBytes()); outStream.write(("Accept: image/gif, image/jpeg, */*\r\n").getBytes()); outStream.write("Accept-Language: zh-CN\r\n".getBytes()); outStream.write(("Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n").getBytes()); outStream.write(("Content-Length: " + dataLength + "\r\n").getBytes()); outStream.write("Connection: Keep-Alive\r\n".getBytes()); outStream.write(("Host: " + url.getHost() + ":" + port + "\r\n").getBytes()); // 請求頭結束,另起一行 outStream.write("\r\n".getBytes()); // 5. 先寫文本參數 outStream.write(textEntity.toString().getBytes()); // 6. 再寫文件數據 for (FormFile uploadFile : files) { StringBuilder fileEntity = new StringBuilder(); fileEntity.append("--").append(BOUNDARY).append("\r\n"); fileEntity.append("Content-Disposition: form-data;name=\"" + uploadFile.getParameterName() + "\";filename=\"" + uploadFile.getFilname() + "\"\r\n"); fileEntity.append("Content-Type: " + uploadFile.getContentType() + "\r\n\r\n"); outStream.write(fileEntity.toString().getBytes()); if (uploadFile.getInStream() != null) { byte[] buffer = new byte[1024]; int len; while ((len = uploadFile.getInStream().read(buffer, 0, 1024)) != -1) { outStream.write(buffer, 0, len); } uploadFile.getInStream().close(); } else { outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); } outStream.write("\r\n".getBytes()); } // 7. 寫結束標誌 outStream.write(endline.getBytes()); outStream.flush(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); boolean ok = reader.readLine().indexOf("200") != -1; outStream.close(); reader.close(); socket.close(); return ok; }

幾點實踐提醒

1)Content-Length 必須準確。手工拼協議時,這個值算錯會導致服務器一直等數據,連接掛死。

2)別忘記主線程限制。從 Android 4.0 開始,網絡請求放在主線程會拋 NetworkOnMainThreadException,必須放到子線程或異步任務裡。

3)記得加權限。AndroidManifest.xml 中需要聲明 android.permission.INTERNET。

4)連接超時要設置。移動網絡環境複雜,不設超時容易讓線程長期阻塞。

把上面這些代碼整理進工具類,日常開發中基本可以直接複用。理解 HTTP 協議的組織方式之後,即使不用任何框架,也能靈活應對各種接口場景。

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