編輯:關於 Android 程式設計
本系列文章均為 A2BGeek 原創,轉載請在明顯處註明出處。
本期專題講解網絡編程。幾乎每個 App 都或多或少有訪問網絡的需求——使用者登入、檔案上傳下載、版本更新等等。本期著重實踐,會有大量可直接取用的程式碼。
HTTP 大概是現在網際網路上使用最廣泛的協議。JDK 的 java.net 套件已提供基本能力:HttpURLConnection。它是 Java 標準類,繼承自 URLConnection,可用於發送 GET 與 POST 請求。
若只需要對某個簡單網址送出請求並取回回應,HttpURLConnection 綽綽有餘。但真實場景往往沒這麼單純:頁面可能需要登入、需要具備相應權限才能訪問,這就涉及 Session 與 Cookie 的處理。用 HttpURLConnection 硬做當然可行,只是自己維護 Cookie 的難度不低。
為了解決這類細節,Apache 提供了 HttpClient 專案。顧名思義,它是一個 HTTP 客戶端(不是瀏覽器),能發送請求、接收回應,但不會快取回應、不執行頁面中的 JavaScript、也不解析頁面內容。
一句話總結:HttpClient 就是增強版的 HttpURLConnection——後者能做的事它全都能做,後者沒提供的某些功能它也有,但同樣只專注於「送請求、收回應、管理連接」這三件事。
這裡說的登入只是把帳號密碼送給伺服器,由伺服器驗證後回傳一個標記(例如 1 代表成功)。真正的登入機制沒這麼簡單,還要維護 Session。下面用四種方式實作同一件事:HttpURLConnection 的 GET 與 POST、HttpClient 的 GET 與 POST。伺服器端選用 Facebook 的開源框架 Tornado,你也可以換成自己熟悉的組合。
public static String HttpURLConnectionGet(String username, String passwd) {
String response = "HttpURLConnectionGet ";
try {
String urlStr = "https://XXX.XXX.XXX.XXX:8888/normalrequest?username="
+ username + "&password=" + passwd;
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine;
while ((readLine = br.readLine()) != null) {
response += readLine;
}
is.close();
br.close();
urlConnection.disconnect();
} catch (Exception e) {
Log.v("a2bgeek", "Exception--->" + e.getMessage());
}
return response;
}
伺服器 IP 這裡用 XXX 代替。GET 的特徵是把參數直接拼在網址後面。
public static String HttpURLConnectionPost(String username, String passwd) {
String response = "HttpURLConnectionPost ";
try {
String urlStr = "https://XXX.XXX.XXX.XXX:8888/normalrequest";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.connect();
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
String content = "username=" + username + "&password=" + passwd;
out.writeBytes(content);
out.flush();
out.close();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine;
while ((readLine = br.readLine()) != null) {
response += readLine;
}
is.close();
br.close();
urlConnection.disconnect();
} catch (Exception e) {
Log.v("a2bgeek", "Exception--->" + e.getMessage());
}
return response;
}
setDoOutput(true) 是 POST 的關鍵——它告訴 HttpURLConnection 你要往伺服器寫資料,getOutputStream() 才不會拋例外。
public static String HttpClientGet(String username, String passwd) {
String response = "HttpClientGet ";
try {
String urlStr = "https://XXX.XXX.XXX.XXX:8888/normalrequest?username="
+ username + "&password=" + passwd;
HttpGet httpGet = new HttpGet(urlStr);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
response += EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
Log.v("a2bgeek", "Exception--->" + e.getMessage());
}
return response;
}
public static String HttpClientPost(String username, String passwd) {
String response = "HttpClientPost ";
try {
HttpPost httpPost = new HttpPost("https://XXX.XXX.XXX.XXX:8888/normalrequest");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", passwd));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
response += EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
Log.v("a2bgeek", "Exception--->" + e.getMessage());
}
return response;
}
用 HttpClient 時 POST 明顯簡潔許多——把參數裝進 NameValuePair 列表交給 UrlEncodedFormEntity 即可,不必自己拼字串。
以 Tornado 實作,不熟悉的讀者請自行搜尋。
# server.py
import tornado.ioloop
import tornado.web
from request import NormalRequestHandler
application = tornado.web.Application([
(r"/normalrequest", NormalRequestHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
# request.py
import tornado.web
class NormalRequestHandler(tornado.web.RequestHandler):
def get(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == 'a2bgeek' and password == '123456':
self.write('login success')
else:
self.write('login fail')
def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == 'a2bgeek' and password == '123456':
self.write('login success')
else:
self.write('login fail')
這裡有一點務必提醒:Android 4.0 之後,涉及網絡的操作不能放在主線程執行,否則會拋出 NetworkOnMainThreadException。必須另開一條線程,或改用 AsyncTask、Thread + Handler 等方式。
上傳一般用 POST。GET 對資料量有限制,只能送很小的內容;POST 理論上沒有限制。
上傳檔案要用 multipart/form-data 格式,手動組出分隔標記:
String boundary = "a2bgeek";
urlConnection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes("--" + boundary);
dos.writeBytes("\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName() + "\"" + "\r\n");
dos.writeBytes("\r\n");
FileInputStream fis = new FileInputStream(file.getPath());
byte[] buffer = new byte[1024 * 1024];
int count;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes("\r\n");
dos.writeBytes("--" + boundary + "--");
dos.flush();
dos.close();
分隔字串必須前後一致,結尾還要多一組「--」表示資料結束。這段格式寫錯是上傳失敗最常見的原因,而錯誤訊息通常只會給你一個 500,很難從中反推。
用 MultipartEntity 就免去了手動拼格式的麻煩:
HttpPost httpPost = new HttpPost(urlStr);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", new FileBody(file));
httpPost.setEntity(multipartEntity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
import tornado.web
import os
class UploadFileHandler(tornado.web.RequestHandler):
def get(self):
self.write('''
<form action="fileupload" enctype="multipart/form-data" method="post">
<input name="file" type="file" /><br />
<input type="submit" value="submit" />
</form>
''')
def post(self):
upload_path = os.path.join(os.path.dirname(__file__), 'files')
if not os.path.exists(upload_path):
os.makedirs(upload_path)
file_metas = self.request.files['file']
for meta in file_metas:
filename = meta['filename']
filepath = os.path.join(upload_path, filename)
with open(filepath, 'wb') as up:
up.write(meta['body'])
self.write('upload success')
寫檔時要用 'wb' 二進位模式,用 'w' 會破壞非文字檔的內容。
下載一般用 GET,其實 POST 也行,兩者沒有本質差異,只是 GET 更方便;用 POST 的話需要在伺服器端另外寫回傳檔案的程式。
int BUFFER_SIZE = 1024 * 1024;
String urlStr = "https://XXX.XXX.XXX.XXX:8888/pic/one.png";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File(
Environment.getExternalStorageDirectory().getPath()
+ "/NetConn/downone.png"));
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
is.close();
fos.close();
HttpGet httpGet = new HttpGet(urlStr);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
FileOutputStream fos = new FileOutputStream(new File(
Environment.getExternalStorageDirectory().getPath()
+ "/NetConn/downtwo.png"));
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
is.close();
fos.close();
分塊讀寫是下載的基本功。若檔案很大,還應搭配 Content-Length 回應標頭計算進度百分比,並在寫檔時考慮斷點續傳。
本期程式碼量較大,大部分已附在文中。另外要補充兩個時代背景:Apache HttpClient 在 Android 5.1 之後已被標記為 deprecated,官方建議改用 HttpURLConnection 或 OkHttp;寫入外部儲存空間也需要 READ/WRITE_EXTERNAL_STORAGE 權限,而在 Android 6.0 之後同樣要執行期動態申請。這些細節在當年寫文章時還不是問題,現在複習時卻是必踩的坑。
Android 開發實戰:Sensor 架構解析與搖一搖功能實作
幾乎所有 Android 裝置都內建了各類感測器,能測量運動、方向與環境條件。這些感測器提供的原始資料精度相當高,非常適合用來監測三維空間中的動作,或追蹤裝置周邊環境的變
Android 自定義 View 實作京東風格垂直輪播文字(跑馬燈)
先看京東客戶端的實際效果: 這篇文章只聚焦在後面那段會上下滾動的文字上,前面的圖示直接用 ImageView 或 TextView 擺上去就好。先看一下我們最終要做出來
Android 九宮格實作:用 GridView 打造三列圖文入口
桌面或功能首頁常見的九宮格入口,在 Android 中最直接的實作方式是 GridView 搭配 SimpleAdapter。以下用一個 3×3 的圖文入口作為範例。
Android Toast 五種實作:打造自訂提示訊息
Toast 是 Android 中常見的輕量提示元件。除了預設樣式,開發者也能自訂位置、加入圖片、使用自訂版面,甚至在其他執行緒中顯示。以下整理五種常見用法。 一、預設樣