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

Android 檔案上傳實戰:HttpURLConnection 與 HttpClient 兩種方案

編輯:關於 Android 程式設計

在 Android 上把檔案上傳到伺服器,主要有兩條路:直接使用 HttpURLConnection,或使用 Android 封裝好的 HttpClient。若只是單純上傳檔案,HttpURLConnection 更為輕量便捷;而需要同時傳送文字與檔案時,HttpClient 搭配 MultipartEntity 則更省事。本文逐一示範這三種做法。

方案一:使用 HttpURLConnection 上傳檔案

核心思路是自己組裝 HTTP 協議內容,將檔案轉換為表單資料流,讓伺服器解析後取得表單資料:

HttpURLConnection con;
try {
    con = (HttpURLConnection) url.openConnection();
    con.setConnectTimeout(C_TimeOut);
    /* 允許 Input、Output,不使用 Cache */
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    /* 設置 method=POST */
    con.setRequestMethod("POST");
    /* 設置請求標頭 */
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Charset", "UTF-8");
    con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    /* 設置 DataOutputStream */
    DataOutputStream ds = new DataOutputStream(con.getOutputStream());
    FileInputStream fStream = new FileInputStream(file);

    /* 每次寫入 1024 bytes */
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int length = -1;
    /* 從檔案讀取資料至緩衝區,並寫入 DataOutputStream */
    while ((length = fStream.read(buffer)) != -1) {
        ds.write(buffer, 0, length);
    }
    fStream.close();
    ds.flush();
    ds.close();
} catch (Exception e) {
    // 處理例外
}

方案二:使用 HttpClient 上傳參數

若只需傳送文字參數,可用 UrlEncodedFormEntity 把參數封裝進請求體:

private static boolean sendPOSTRequestHttpClient(String path,
        Map<String, String> params) throws Exception {
    // 封裝請求參數
    List<NameValuePair> pair = new ArrayList<NameValuePair>();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            pair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    // 把請求參數變成請求體部分
    UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
    // 使用 HttpPost 設置 URL 路徑
    HttpPost post = new HttpPost(path);
    post.setEntity(uee);
    // 發送請求並接收響應
    DefaultHttpClient dhc = new DefaultHttpClient();
    HttpResponse response = dhc.execute(post);
    if (response.getStatusLine().getStatusCode() == 200) {
        return true;
    }
    return false;
}

方案三:使用 HttpClient 上傳文字與檔案

要同時傳送文字與檔案,HttpClient 搭配 MultipartEntity 最為方便,但需先導入 apache-mime4j-0.6.jar 與 httpmime-4.0.jar 兩個套件:

// 封裝請求參數
MultipartEntity mpEntity = new MultipartEntity();
if (params != null && !params.isEmpty()) {
    for (Map.Entry<String, String> entry : params.entrySet()) {
        StringBody par = new StringBody(entry.getValue());
        mpEntity.addPart(entry.getKey(), par);
    }
}
// 加入圖片
if (!imagepath.equals("")) {
    FileBody file = new FileBody(new File(imagepath));
    mpEntity.addPart("photo", file);
}
// 設置 URL 並發送
HttpPost post = new HttpPost(path);
post.setEntity(mpEntity);
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);

其中 FileBody 能把檔案封裝進表單,實現附件上傳;StringBody 則負責文字欄位。三種方案各有側重:追求輕量選 HttpURLConnection,純文字參數用 UrlEncodedFormEntity,而圖文並傳則首選 MultipartEntity。本文原始作者為安客成。

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