編輯:關於 Android 程式設計
Android 中的網絡操作與 Java SE 裡並沒有本質差別,Java 中的大量網絡代碼幾乎可以直接搬過來用。動手之前,先把幾個關鍵概念理清楚。
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 請求:把參數拼到地址後發送
* @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 表單請求
* @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。少任何一個,服務器都會收到畸形請求。
/**
* 向服務器發送 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 請求
*/
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 請求
*/
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 幫我們省掉了設置請求頭和拼實體的麻煩,代碼量明顯更少。
原理不神秘:瀏覽器上傳表單時,底層會把數據組織成 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
1)Content-Length 必須準確。手工拼協議時,這個值算錯會導致服務器一直等數據,連接掛死。
2)別忘記主線程限制。從 Android 4.0 開始,網絡請求放在主線程會拋 NetworkOnMainThreadException,必須放到子線程或異步任務裡。
3)記得加權限。AndroidManifest.xml 中需要聲明 android.permission.INTERNET。
4)連接超時要設置。移動網絡環境複雜,不設超時容易讓線程長期阻塞。
把上面這些代碼整理進工具類,日常開發中基本可以直接複用。理解 HTTP 協議的組織方式之後,即使不用任何框架,也能靈活應對各種接口場景。
Android 磁碟緩存 DiskLruCache 完全指南與自製圖片加載器
DiskLruCache 是一套硬碟(磁碟)緩存方案,淘汰策略與 LruCache 同源,都基於 LRU 演算法——最近最少使用的數據優先被清掉。 需要特別說明的是,這個
安卓 JNI 進階實戰:動態註冊 native 方法與 JNI 資料型別全解析
前言 或許你已經能跑通最簡單的 JNI 呼叫了。說實話這不算什麼,網路上這類教學一大堆。雖然 JNI 大多數時候用不到我們安卓工程師親自處理,畢竟門檻不低,但既然要用,
Android 寄送電子郵件:使用 Android-Mail 套件實作 SMTP 寄信
在 Android 應用中寄送電子郵件,可以透過 Android-Mail 相關套件完成。相較於自行處理複雜的 SMTP 協商,使用現成套件能快速實現寄信功能。 前置準
TaintDroid深入剖析之啟動篇
1 背景知識 1.1 Android 平台軟件動態分析現狀 眾所周知,在計算機領域中,所有的軟件分析方法都可以歸為靜態分析和動態分析兩大類,Android 平台也不例外。