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

Android 網絡編程學習與實戰(一):上傳單個或多個文件

編輯:關於 Android 程式設計

1. HttpURLConnection 類概述

HttpURLConnection 是一個用於 HTTP 協議的 URLConnection,主要用來透過網路收發資料。它支援任意類型與長度的資料,特別適合收發長度事先未知的資料流。其使用遵循以下模式:

首先透過 URL 類的 openConnection() 取得 HttpURLConnection 實例並做強制轉型;接著準備請求——請求的基本屬性是 URL,請求標頭可包含證書、內容類型、session 與 cookie 等元資料,若有請求體則須呼叫 setDoOutput(true),再透過 getOutputStream() 取得輸出流寫入資料;然後讀取響應——響應標頭通常包含內容類型與長度、修改日期等元資料,響應體則可從 getInputStream() 返回的流中讀取,若無響應體則返回空;最後在讀取完畢後呼叫 disconnect() 釋放連接所占用的資源。

依上述步驟,先寫一個實驗程式:向伺服器發送請求並取得響應,再將響應顯示於 TextView 中。

 public class MainActivity extends AppCompatActivity { URL url = null; TextView textView; Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { textView.setText(msg.getData().getString("name")); return true; } }); new Thread(new Runnable() { HttpURLConnection connection; @Override public void run() { try { url = new URL("https://www.baidu.com/?tn=57095150_1_oem_dg"); connection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line=bufferedReader.readLine())!=null){ stringBuilder.append(line); } Message message = new Message(); Bundle bundle= new Bundle(); bundle.putString("name",stringBuilder.toString()); message.setData(bundle); handler.sendMessage(message); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { connection.disconnect(); } } }).start(); } }

這段程式碼會訪問該網址並把取得的內容顯示到 TextView。幾個重點:Android 的 UI 執行緒不可執行網路等耗時工作,因此需放在子執行緒中;TextView 內容可能一頁顯示不完,最好放進 ScrollView 以便捲動查看;使用 Handler 與 Message 更新 UI;別忘了加入網路權限:

 

1.2 基於 HTTPS 的安全連接

同樣使用 openConnection() 取得 HttpsURLConnection 實例,此時 URL 須以「https://」開頭。它允許覆寫 HostnameVerifier 與 SSLSocketFactory 介面:支援 SSLSocketFactory 的應用程式可提供自訂的 X509TrustManager 用於憑證鏈驗證,以及自訂的 X509KeyManager 用於客戶端驗證。

1.3 發送內容

為了上傳資料,須以 setDoOutput(true) 將連接設為輸出。為了獲得更好的效能,若資料長度事先可知,可使用 setFixedLengthStreamingMode(int) 設定長度;若長度未知,則使用 setChunkedStreamingMode(int)。否則 HttpURLConnection 會先緩衝完整的請求體再發送,造成記憶體浪費與延遲增加。

2. 上傳一張或多張圖片到伺服器

具備上述理論基礎後,上傳圖片便成為可能。要完成這功能,先得解決兩個問題:向哪個伺服器上傳?伺服器如何接收?我的做法是自建 Apache 伺服器,接收端用 PHP(因為略有涉獵,其他 Web 端語言則一無所知)。

上傳的檔案則簡單放在 assets 目錄下,透過 AssetManager 管理十分方便。

2.1 把 assets 目錄下的一張圖片顯示到 ImageView

這是很簡單的一步,為了專案的完整性還是列出來。這是一個讀取 assets 目錄檔案的方法:

 public Bitmap readAssetsFile(String name){ Bitmap image = null; InputStream inputStream = null; try { inputStream = getResources().getAssets().open(name); image = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } finally { if(inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return image; }

2.2 PHP 保存上傳的檔案

這個過程分為幾步:先架好伺服器(建議直接裝 wamp,簡單易用)並啟動;用 HTML 上傳檔案、以 PHP 接收,確保 PHP 能正常工作;最後編寫並測試 Android 端程式碼。

先用 HTML 上傳、PHP 接收的測試程式碼。HTML 部分非常簡單,就是一個上傳表單:

     file upload   

它的樣子如下:

PHP 程式碼如下:

 "; echo "Type: ".$_FILES["myfile"]["type"]."
"; echo "Size: ".($_FILES["myfile"]["size"]/1024)." Kb
"; echo "Temp file: " . $_FILES["myfile"]["tmp_name"]."
"; if (file_exists("D:/wamp/www/"."upload/" . $_FILES["myfile"]["name"])) { echo $_FILES["myfile"]["name"]." already exists. "; } else { if(move_uploaded_file($_FILES["myfile"]["tmp_name"],"D:/wamp/www/"."upload/" . $_FILES["myfile"]["name"])){ echo "Stored in: " . "upload/" . $_FILES["myfile"]["name"]; }else{ echo "Store failed"; } } ?>

這段程式碼先把上傳檔案的資訊印出來以便除錯,接著判斷該檔案在伺服器 upload 目錄下是否存在:存在就什麼都不做,不存在則存起來。這裡要注意:檔案路徑要用絕對路徑,否則會報錯。就這樣簡單的程式碼,便實現了檔案的上傳與保存。這主要用來驗證伺服器端能正常接收並保存檔案,有了這層保障,就能專心處理 Android 端程式碼了。

以下是接收後的頁面與上傳情況:

2.3 Android 端上傳檔案的程式碼

正式寫程式前,先複習第一小節:我們已知道如何訪問伺服器、取得響應、發送資料塊。上傳圖片本質上就是把一個資料塊發送給伺服器,因此基礎知識已具備。想更透徹理解 HttpURLConnection,不妨耐心把 API 文件看完——寫程式不必著急。

2.3.1 效能

除了 1.3 提到的設定資料長度外,還需注意:這個類返回的輸入輸出流未經緩衝,大多數時候需包裝為緩衝流(若是直接讀寫大塊資料,也可忽略)。為了減少延遲,這個類可能對多個請求/響應對重用同一個底層 socket,導致 HTTP 連接長時間保持開啟;若不想如此,可將 http.keepAlive 系統屬性設為 false,並用 http.maxConnections 設定每個到伺服器的最大空閒連接數。預設情況下,這個類會用 gzip 自動壓縮請求,並在呼叫 getInputStream() 時自動解壓;此時 Content-Encoding 與 Content-Length 需被聲明。若要關閉 gzip,可使用:

 urlConnection.setRequestProperty("Accept-Encoding", "identity");

getContentLength() 可取得傳輸位元組數,但不能用來判斷 getInputStream() 中可讀取的位元組數;正確做法是不斷呼叫 read() 直到返回 -1,表示資料讀完。

2.3.2 處理登錄與 HTTP 認證

有些 Wi-Fi 網路會在使用者登入前阻斷網路訪問,這種登入頁通常以 HTTP 重定向實現。可用 getUrl() 檢查連接是否被意外重定向,此檢查須在收到響應標頭前進行:

 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); if (!url.getHost().equals(urlConnection.getURL().getHost())) { // 發生了重定向,可引導使用者到瀏覽器登入 } finally { urlConnection.disconnect(); } }

HttpURLConnection 支援 HTTP 基本認證,可透過 Authenticator 進行虛擬機級別的認證處理:

 Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); } });

除非使用 HTTPS,否則這並非安全的認證方式——特別是使用者名稱、密碼、請求與響應都未加密便在網路間傳遞。

2.4 RFC 1867 協議

HTTP 原本不支援檔案上傳,為此 RFC 1867 對其做了修改,主要針對請求標頭與請求體兩方面。

2.4.1 請求標頭的修改

Content-Type 由原本的 application/x-www-form-urlencoded 改為:

 Content-Type:multipart/form-data; boundary=-------7d71f4234700b8

其中 multipart/form-data 是必須的;boundary 在請求體中使用,它會把請求體分成多個塊,每塊代表一塊獨立資料(或稱一個檔案)。

2.4.2 請求體的修改

 -----------------------------7d71f4234700b8 Content-Disposition: form-data; name="formhash" 59329e15 -----------------------------7d71f4234700b8 Content-Disposition: form-data; name="isblog" -----------------------------7d71f4234700b8 Content-Disposition: form-data; name="fid" 104 -----------------------------7d71f4234700b8

可見請求體被分成多個塊,每塊代表一個獨立檔案。這裡的 name 需與 PHP 中 $_FILES[name] 保持一致,也與 input 標籤的 name 屬性一致,後面還可加上檔名、檔案長度等資訊。

2.5 正式撰寫 Android 程式碼

2.5.1 上傳一個檔案

Android 端的難點在於設定 HTTP 與 RFC 1867 協議的參數。以下列一個完整的 POST 請求格式為例,逐條對應設定:

 POST /upload_file/UploadFile HTTP/1.1 Accept: text/plain, */* Accept-Language: zh-cn Host: 192.168.29.65:80 Content-Type:multipart/form-data;boundary=---------------------------7d33a816d302b6 User-Agent: Mozilla/4.0 (compatible; OpenOffice.org) Content-Length: 424 Connection: Keep-Alive -----------------------------7d33a816d302b6 Content-Disposition:form-data; name="userfile1"; filename="E:\s"Content-Type: application/octet-stream abbXXXccc -----------------------------7d33a816d302b6 Content-Disposition: form-data; name="text1" foo -----------------------------7d33a816d302b6--

下面的程式碼逐條配置了模板中的各項條目,註解中有詳細說明:

 package com.konka.networktest; import android.content.Context; import android.content.res.AssetManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Utils { public static void doupLoadPic(Context context, Handler handler){ final String end = "\r\n"; final String twoHyphens = "--"; final String boundary = "******"; URL url = null; HttpURLConnection httpURLConnection = null; try { url = new URL("https://192.168.0.103:8088/php/fileupload.php"); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setChunkedStreamingMode(128 * 1024);// 提高效能 httpURLConnection.setDoOutput(true); // 允許輸出 httpURLConnection.setDoInput(true); // 允許讀入 httpURLConnection.setUseCaches(false); // 不使用緩衝 // 設定 rfc1867 請求頭 httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Accept","text/plain, */*"); httpURLConnection.setRequestProperty("Accept-Language","zh-cn"); httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary); httpURLConnection.setRequestProperty("Connection","Keep-Alive"); // 設定請求體 DataOutputStream dout = new DataOutputStream(httpURLConnection.getOutputStream()); dout.writeBytes("--"+boundary+end); dout.writeBytes("Content-Disposition:form-data;"); dout.writeBytes("name="+"\"myfile\";"); dout.writeBytes("filename="+"\"one.jpg\""); dout.writeBytes(end); dout.writeBytes(end); // 讀取檔案並寫入請求體 AssetManager am = context.getAssets(); InputStream inputStream = am.open("one.jpg"); byte[] buffer = new byte[8192]; int count = 0; while ((count = inputStream.read(buffer)) != -1) { dout.write(buffer, 0, count); } dout.writeBytes(end+"--"+boundary+end); // 讀取伺服器返回的資料 BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8")); StringBuilder builder = new StringBuilder(); String result; while((result = br.readLine())!= null){ builder.append(result); } Message message = new Message(); Bundle bundle= new Bundle(); bundle.putString("name",builder.toString()); message.setData(bundle); handler.sendMessage(message); br.close(); inputStream.close(); dout.close(); httpURLConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

這個類中的 handler 用於通知 UI 已收到資料。注意這裡並未處理檔案類型,伺服器端也沒檢查,需要的話可自行補上。

2.5.2 上傳多個檔案

只要會上傳一個檔案,並理解上傳多個檔案就是用「--」+boundary 把多個檔案分開、再於分隔後加上檔案類型與檔名等資訊即可。以下是新增的程式碼:

 // 發送第二個檔案 dout.writeBytes("Content-Disposition:form-data;"); dout.writeBytes("name="+"\"myfile1\";"); dout.writeBytes("filename="+"\"two.jpg\""); dout.writeBytes(end); dout.writeBytes(end); InputStream inputStream1 = am.open("two.jpg"); while ((count = inputStream1.read(buffer)) != -1) { dout.write(buffer, 0, count); } inputStream1.close(); dout.writeBytes(end+"--"+boundary+end);

伺服器端也只是把接收一個檔案的程式碼複製一份:

 // 第二個檔案 echo "second file arrived"; echo "Upload: ".$_FILES["myfile1"]["name"]." "; echo "Type: ".$_FILES["myfile1"]["type"]." "; echo "Size: ".($_FILES["myfile1"]["size"]/1024)." Kb "; if (file_exists("D:/wamp/www/"."upload/" . $_FILES["myfile1"]["name"])) { echo $_FILES["myfile1"]["name"]." already exists. "; } else { if(move_uploaded_file($_FILES["myfile1"]["tmp_name"],"D:/wamp/www/"."upload/" . $_FILES["myfile1"]["name"])){ echo "Stored in: " . "upload/" . $_FILES["myfile1"]["name"]; }else{ echo "Store failed"; } }

手機端收到的資訊如下:

伺服器端則多出兩個檔案:

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