編輯:關於 Android 程式設計
行動應用幾乎一定要和伺服器打交道,發請求就成了基本功。這裡梳理四種常見做法,兩兩一組:Java 原生的 HttpURLConnection,以及 Apache 的 HttpClient,各自都有 GET 與 POST 兩種形式。示例代碼都放在單元測試裡跑,方便直接驗證。
參數直接拼在 URL 上,打開連接、設定超時、判斷回應碼即可。
// GET 方式請求
public static void requestByGet() throws Exception {
String path = "https://www.jb51.net/logins.jsp?id=helloworld&pwd=android";
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(5 * 1000); // 連接超時
urlConn.connect();
if (urlConn.getResponseCode() == HTTP_200) {
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式請求失敗");
}
urlConn.disconnect();
}
POST 有幾個必須設定的開關:允許輸出、關閉緩存、請求方法改為 POST,並通過 DataOutputStream 把參數寫出去。
// POST 方式請求
public static void requestByPost() throws Throwable {
String path = "https://www.jb51.net/logins.jsp";
// 參數需先做 URL 編碼
String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
+ "&pwd=" + URLEncoder.encode("android", "UTF-8");
byte[] postData = params.getBytes();
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(5 * 1000);
urlConn.setDoOutput(true); // POST 必須允許輸出
urlConn.setUseCaches(false); // POST 不使用緩存
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.connect();
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
if (urlConn.getResponseCode() == HTTP_200) {
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");
Log.i(TAG_POST, new String(data, "UTF-8"));
} else {
Log.i(TAG_POST, "Post方式請求失敗");
}
}
Apache 這一路的寫法更精簡,一行 execute 就把請求發出去了。
// HttpGet 方式請求
public static void requestByHttpGet() throws Exception {
String path = "https://www.jb51.net/logins.jsp?id=helloworld&pwd=android";
HttpGet httpGet = new HttpGet(path);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpGet);
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");
}
}
參數用 NameValuePair 列表承載,封裝成 UrlEncodedFormEntity 後掛到請求上。
// HttpPost 方式請求
public static void requestByHttpPost() throws Exception {
String path = "https://www.jb51.net/";
HttpPost httpPost = new HttpPost(path);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "helloworld"));
params.add(new BasicNameValuePair("pwd", "android"));
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpPost);
if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回數據如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");
}
}
以上只是核心片段,測試時在測試類中調用對應方法即可。兩套方案各有取捨:HttpURLConnection 屬於標準庫、實現輕量,有利於省電省內存;HttpClient 的 API 更省心,但新版 Android 已不再推薦。新專案建議直接上 OkHttp 或 Retrofit。
Android Activity 生命週期完全解析:七大回呼與實測驗證
Google 官方 Android 開發文件在描述生命週期時,給出了這樣一張圖: Activity 類別中定義的七個回呼方法,涵蓋了活動生命週期的每一個環節。以下逐一說
讀取 Android 聯絡人並依字母分組展示(二)
目標:讓相同首字母的聯絡人歸在同一組 上一篇我們把聯絡人讀了出來、排好了序,但清單還是一整片到底。這一階段要做的,是在滑動時讓右側出現字母索引,並在切換分組的位置插入分類
Android ListView 分頁加載數據實戰:滑到底自動載入更多
熟悉 Android 的朋友都知道,不管是微博客戶端還是新聞客戶端,都離不開列表元件。可以說 ListView 是 Android 在資料展現方面最重要的元件之一。今天我
Android 向上推送式菜單實作
在百度地圖等需要保留手勢操作的應用中,側滑菜單可能與地圖手勢衝突。此時可改用向上推拉的菜單,透過按鈕觸發顯示與隱藏。 實作思路 版面配置可包含兩個主要區域:主視圖與菜