編輯:關於 Android 程式設計
HTTP 協定可能是目前網際網路上使用最廣泛、最重要的協定,越來越多 Java 應用需要直接透過 HTTP 存取網路資源。Android 提供了兩套工具:JDK 標準的 HttpURLConnection,以及 SDK 內建的 Apache HttpClient。
HttpURLConnection 是 Java 標準類,屬於 java.net 套件。它提供基本的 HTTP 存取能力,但封裝層次低,用起來比較原始。
HttpClient 是 Apache 的開源專案,Android SDK 內建了這個模組。它支援當時最新的 HTTP 協定規格與建議,把請求標頭、參數、實體內容、回應都做了完整封裝,能快速開發出功能完整的 HTTP 程式。
結論很清楚:功能豐富度與靈活度上,HttpClient 明顯勝出,特別是需要自訂請求方法或高級控制時。
String urlAddress = "https://192.168.1.102:8080/AndroidServer/login.do";
URL url;
HttpURLConnection uRLConnection;
// 送出 GET 請求
public String doGet(String username, String password) {
String getUrl = urlAddress + "?username=" + username + "&password=" + password;
try {
url = new URL(getUrl);
uRLConnection = (HttpURLConnection) url.openConnection();
InputStream is = uRLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 送出 POST 請求
public String doPost(String username, String password) {
try {
url = new URL(urlAddress);
uRLConnection = (HttpURLConnection) url.openConnection();
uRLConnection.setDoInput(true);
uRLConnection.setDoOutput(true);
uRLConnection.setRequestMethod("POST");
uRLConnection.setUseCaches(false);
uRLConnection.setInstanceFollowRedirects(false);
uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uRLConnection.connect();
DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
String content = "username=" + username + "&password=" + password;
out.writeBytes(content);
out.flush();
out.close();
InputStream is = uRLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String urlAddress = "https://192.168.1.102:8080/qualityserver/login.do";
public String doGet(String username, String password) {
String getUrl = urlAddress + "?username=" + username + "&password=" + password;
HttpGet httpGet = new HttpGet(getUrl);
HttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpGet);
if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity he = ht.getEntity();
InputStream is = he.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
return response;
} else {
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}
public String doPost(String username, String password) {
HttpPost httpPost = new HttpPost(urlAddress);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
HttpEntity he;
try {
he = new UrlEncodedFormEntity(params, "gbk");
httpPost.setEntity(he);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
HttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpPost);
if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
return response;
} else {
return "error";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "exception";
} catch (IOException e) {
e.printStackTrace();
return "exception";
}
}
對照之下差異很明顯:HttpClient 用 NameValuePair 集合處理 POST 參數,不必自己拼字串;用 StatusLine 判斷狀態碼;DefaultHttpClient 內建連線池管理。程式碼量相近,但可讀性與可維護性更好。
Servlet 端輸出 JSON:
resp.setContentType("text/json");
resp.setCharacterEncoding("UTF-8");
List<UserBean> list = toDo.queryUsers(mySession);
JSONArray array = new JSONArray();
for (UserBean bean : list) {
JSONObject obj = new JSONObject();
try {
obj.put("username", bean.getUserName());
obj.put("password", bean.getPassWord());
} catch (Exception e) { }
array.add(obj);
}
pw.write(array.toString());
Android 端接收並解析:
String urlAddress = "https://192.168.1.102:8080/qualityserver/result.do";
String body = getContent(urlAddress);
JSONArray array = new JSONArray(body);
for (int i = 0; i < array.length(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
try {
JSONObject obj = array.getJSONObject(i);
userName = obj.getString("username");
passWord = obj.getString("password");
} catch (JSONException e) {
e.printStackTrace();
}
map.put("username", userName);
map.put("password", passWord);
listItem.add(map);
}
// 設定 adapter
SimpleAdapter simple = new SimpleAdapter(this, listItem,
android.R.layout.simple_list_item_2,
new String[] { "username", "password" },
new int[] { android.R.id.text1, android.R.id.text2 });
listResult.setAdapter(simple);
// 帶超時設定的 GET
private String getContent(String url) throws Exception {
StringBuilder sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
}
return sb.toString();
}
兩者都不再是首選。Android 4.4(API 19)起官方文件已明確建議改用 HttpURLConnection,Apache HttpClient 在 Android 5.1(API 22)被標記為 deprecated,Android 6.0 起更是從平台移除,需要自行把 jar 檔打包進專案才能用。
官方當初建議 HttpURLConnection 的理由是:它對多數應用只需 GET 與 POST 的場景夠用,且能與系統底層的連線管理、快取機制整合得更好,省電與省流量表現較佳。
若確實需要新版 HttpClient,可加入 org.apache.httpcomponents:httpclient 依賴並在 build.gradle 中啟用 useLibrary 'org.apache.http.legacy',但這只適合維護既有程式碼。
新專案的建議:優先考慮 HttpURLConnection 搭配 ExecutorService 處理非同步,或直接使用成熟網路庫——Volley 適合高頻小請求與圖片載入,Retrofit 搭配 OkHttp 則是目前的社群主流,它用註解宣告介面、自動處理 JSON 序列化,並與 RxJava、Kotlin 協程無縫整合,能省下大量樣板程式。
另外提醒一個與框架無關但常被忽略的問題:範例中把帳號密碼直接拼進 query string,等同在網路上裸奔。任何憑證傳輸都必須走 HTTPS,並避免出現在 URL 或日誌中。
Java 4 Android 開發教程(三):環境變數與 JDK 基本概念
開始寫 Java 之前,必須先搞懂環境變數、JRE 與 JVM 的關係。這篇文章把入門階段最容易混淆的幾個名詞一次講清楚。 什麼是環境變數 環境變數是作業系統用來存放執
Shiro 回顧筆記:用 ini 檔動手驗證授權機制
一、Shiro 的授權是怎麼跑的 授權流程可以概括成一句話:先問「你是誰」,再問「你能做什麼」。而跟認證環節類似,Shiro 在判定權限時,最後仍然是回到 Realm 去
Android 5.X 全新特性巡禮:Material Design 常用組件實戰
要在項目中使用 Android 5.X 的新特性,第一步是導入 5.X 的支持包。 FloatingActionButton 這是 Material Design 設計
用 ES 檔案瀏覽器直接播電腦上的共享媒體檔
手機容量再大也很難贏過電腦,一部藍光畫質的電影常常就是裝不下。但你還是想看,怎麼辦?其實不必先轉檔再傳,讓 ES 檔案瀏覽器直接讀電腦上的共享資料夾就行。以下示範。 安卓