編輯:Android 資訊
大多數 Android 應用都需要與伺服器互動來取得資料。若採用 HTTP 協議收發資料,便離不開 HttpURLConnection 與 HttpClient。Android 主要提供了這兩種方式來完成 HTTP 操作,且兩者都支援 HTTPS 協議、以串流方式上傳下載、設定逾時、IPv6 以及連線池等功能。
不過在 Google 發佈 6.0 時,曾宣告原生移除 HttpClient。筆者認為 Google 大概率仍會提供對應的 jar 包作為支援,畢竟它在向下相容方面一向做得不錯,開發者在選擇網路方案時,仍有依自己偏好挑選的空間。

先來看看如何用 HttpURLConnection 處理一個簡單的網路請求。
// Get方式請求 public static void requestByGet() throws Exception { String path = "10.128.7.34:3000/name=helloworld&password=android"; // 新建一個URL對象 URL url = new URL(path); // 打開一個HttpURLConnection連接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 設置連接超時時間 urlConn.setConnectTimeout(6 * 1000); // 開始連接 urlConn.connect(); // 判斷請求是否成功 if (urlConn.getResponseCode() == HTTP_200) { // 獲取返回的數據 byte[] data = readStream(urlConn.getInputStream()); Log.i(TAG_GET, new String(data, "UTF-8")); } else { Log.i(TAG_GET, "Get方式請求失敗"); } // 關閉連接 urlConn.disconnect(); }
// Post方式請求 public static void requestByPost() throws Throwable { String path = "https://10.128.7.34:3000/login"; // 請求的參數轉換為byte數組 String params = "name+ URLEncoder.encode("helloworld", "UTF-8") + "&password=" + URLEncoder.encode("android", "UTF-8"); byte[] postData = params.getBytes(); // 新建一個URL對象 URL url = new URL(path); // 打開一個HttpURLConnection連接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 設置連接超時時間 urlConn.setConnectTimeout(5 * 1000); // Post請求必須設置允許輸出 urlConn.setDoOutput(true); // Post請求不能使用緩存 urlConn.setUseCaches(false); // 設置為Post請求 urlConn.setRequestMethod("POST"); urlConn.setInstanceFollowRedirects(true); // 配置請求Content-Type urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // 開始連接 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, new String(data, "UTF-8")); } else { Log.i(TAG_POST, "Post方式請求失敗"); } }
關於 HttpURLConnection 的相關開源工程
既然 Google 已明確推薦開發者使用 HttpURLConnection,背後想必有其道理。
xUtils3
這裡要推薦的是我們都很熟悉的開源專案 xUtils 的「弟弟」——xUtils3。xUtils 涵蓋了 view 注入、圖片處理、資料庫操作與網路請求封裝,其網路請求基於 HttpClient;而 xUtils3 的網路請求則改用 HttpURLConnection,這裡我們重點聊聊 xUtils3。
RequestParams params = new RequestParams("https://10.128.7.34:3000/upload"); // 加到url裡的參數, https://xxxx/s?wd=xUtils params.addQueryStringParameter("wd", "xUtils"); // 添加到請求 body 體的參數, 只有 POST, PUT, PATCH, DELETE 請求支持. // params.addBodyParameter("wd", "xUtils"); // 使用 multipart 表單上傳文件 params.setMultipart(true); params.addBodyParameter( "file", new File("/sdcard/test.jpg"), null); // 如果文件沒有擴展名, 最好設置contentType 參數. params.addBodyParameter( "file2", new FileInputStream(new File("/sdcard/test2.jpg")), "image/jpeg", // 測試中文文件名 "你+& /" 好.jpg"); // InputStream 參數獲取不到文件名, 最好設置, 除非服務端不關心這個參數. x.http().post(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show(); } @Override public void onError(Throwable ex, boolean isOnCallback) { Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show(); } @Override public void onCancelled(CancelledException cex) { Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show(); } @Override public void onFinished() { } });
具備 cache 功能
RequestParams params = new RequestParams("https://10.128.7.34:3000/upload"); params.wd = "xUtils"; // 默認緩存存活時間, 單位:毫秒.(如果服務沒有返回有效的max-age 或 Expires) params.setCacheMaxAge(1000 * 60); Callback.Cancelable cancelable // 使用 CacheCallback, xUtils 將為該請求緩存數據. = x.http().get(params, new Callback.CacheCallback<String>() { private boolean hasError = false; private String result = null; @Override public boolean onCache(String result) { // 得到緩存數據, 緩存過期後不會進入這個方法. // 如果服務端沒有返回過期時間, 參考params.setCacheMaxAge(maxAge)方法. // // * 客戶端會根據服務端返回的 header 中 max-age 或 expires 來確定本地緩存是否給 onCache 方法. // 如果服務端沒有返回 max-age 或 expires, 那麼緩存將一直保存, 除非這裡自己定義了返回false的 // 邏輯, 那麼xUtils將請求新數據, 來覆蓋它. // // * 如果信任該緩存返回 true, 將不再請求網絡; // 返回 false 繼續請求網絡, 但會在請求頭中加上ETag, Last-Modified等信息, // 如果服務端返回 304, 則表示數據沒有更新, 不繼續加載數據. // this.result = result; return false; // true: 信任緩存數據, 不在發起網絡請求; false 不信任緩存數據. } @Override public void onSuccess(String result) { // 注意: 如果服務返回 304 或 onCache 選擇了信任緩存, 這裡將不會被調用, // 但是 onFinished 總會被調用. this.result = result; } @Override public void onError(Throwable ex, boolean isOnCallback) { hasError = true; Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show(); if (ex instanceof HttpException) { // 網絡錯誤 HttpException httpEx = (HttpException) ex; int responseCode = httpEx.getCode(); String responseMsg = httpEx.getMessage(); String errorResult = httpEx.getResult(); // ... } else { // 其他錯誤 // ... } } @Override public void onCancelled(CancelledException cex) { Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show(); } @Override public void onFinished() { if (!hasError && result != null) { // 成功獲取數據 Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show(); } } });
post 請求只需改成 post 方式並提交相應參數即可,篇幅所限便不再逐一列舉。從以上程式碼不難看出,用 xUtils 發請求十分省事,只需在回呼函式裡處理業務邏輯,無須操心執行緒問題,極大地解放了生產力。其 Android Studio Gradle 引用方式如下:
compile 'org.xutils:xutils:3.1.+'
Volley
在 Android 2.3 及以上版本使用的是 HttpURLConnection,2.2 及以下版本才用 HttpClient。以當今手機的發展速度,我們早已不必再考慮 Android 2.2。
簡單提供幾個 Volley 的範例:
//簡單的 GET 請求 mQueue = Volley.newRequestQueue(getApplicationContext()); mQueue.add(new JsonObjectRequest(Method.GET, url, null, new Listener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "response : " + response.toString()); } }, null)); mQueue.start();
//對 ImageView 的操作 ImageListener listener = ImageLoader.getImageListener(imageView, android.R.drawable.ic_launcher, android.R.drawable.ic_launcher); mImageLoader.get(url, listener); //對 ImageView 網絡加載的處理 mImageView.setImageUrl(url, imageLoader);
當然我們也可以定製自己的 request
mRequestQueue.add( new GsonRequest(url, ListResponse.class, null, new Listener() { public void onResponse(ListResponse response) { appendItemsToList(response.item); notifyDataSetChanged(); } } }
同樣地,我們來看看 HttpClient 的簡單請求。
// HttpGet 方式請求 public static void requestByHttpGet() throws Exception { String path = "https://10.128.7.34:3000/name=helloworld&password=android"; // 新建 HttpGet 對象 HttpGet httpGet = new HttpGet(path); // 獲取 HttpClient 對象 HttpClient httpClient = new DefaultHttpClient(); // 獲取 HttpResponse 實例 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 方式請求失敗"); } }
// HttpPost 方式請求 public static void requestByHttpPost() throws Exception { String path = "https://reg.163.com/login"; // 新建 HttpPost 對象 HttpPost httpPost = new HttpPost(path); // Post 參數 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "helloworld")); params.add(new BasicNameValuePair("password", "android")); // 設置字符集 HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 設置參數實體 httpPost.setEntity(entity); // 獲取 HttpClient 對象 HttpClient httpClient = new DefaultHttpClient(); // 獲取 HttpResponse 實例 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 方式請求失敗"); } }
關於 HttpClient 的相關開源工程
HttpClient 同樣擁有大量優秀的開源專案,如 afinal、xUtils 以及 AsyncHttpClient,都能為開發者提供現成的輪子。由於 xUtils 是在 afinal 基礎上重寫的,如今 xUtils3 又有取代 xUtils 之勢,這裡我們簡單介紹一下 AsyncHttpClient。
AsyncHttpClient
顧名思義,AsyncHttpClient 尤其擅長處理非同步 Http 請求,並以匿名內部類處理回呼結果。所有非同步請求都運行於非 UI 執行緒,不會阻塞介面操作,透過執行緒池處理併發請求,支援檔案上傳下載與自動打包 JSON 格式的回應結果,使用起來十分便利。
//GET請求 AsyncHttpClient client = new AsyncHttpClient(); //當然這裡也可以換成 new JsonHttpResponseHandler(),我們就能直接獲得 JSON 數據了。 client.get("https://www.google.com", new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is "200 OK" } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried } });
//POST 請求 AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); //同上,這裡一樣可以改成處理 JSON 數據的方法 client.get("https://www.google.com", params, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { System.out.println(response); } @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) { Log.d("ERROR", error); } } );
仔細對照會發現,AsyncHttpClient 的用法異常簡潔,主要透過回呼方法處理成功或失敗後的邏輯。細想之下,xUtils 的處理方式與此頗為相似,可見好用的設計總能廣受青睞。
如果想同時具備兩種請求方式的能力,那麼 OkHttp 可謂最佳方案。
OkHttp 在網路請求領域口碑出眾,連 Google 自己也在使用。雖然 6.0 移除了 HttpClient 的 API,但憑藉 OkHttp 的影響力與強大功能,你無需重寫程式中的網路碼即可遷移。更關鍵的是,OkHttp 幾乎實現了與 java.net.HttpURLConnection 一致的 API;若你原先使用 Apache HttpClient,OkHttp 也提供了對應的 okhttp-apache 模組。凡此種種都足以彰顯它的強大,以下是一些範例。
簡單代碼實例
//GET 請求 OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }
//POST 請求 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }
Android Studio Gradle 使用方式:
compile 'com.squareup.okhttp:okhttp:2.7.0'
Android 開發離不開網路,在行動互聯時代,搶佔終端入口變得至關重要。無論選擇 HttpURLConnection 還是 HttpClient,都能勝任與伺服器溝通的任務,關鍵在於依場景挑選最合適的方案。
做了兩年半 Android 開發,這 18 條經驗我想早點告訴你
2014 年決定投入 Android 開發的那一天,我到現在都還記得——那是人生中數一數二正確的決定。一晃兩年半過去了。 剛入行的時候,沒有人告訴我什麼是對的做法。我犯過
動手封裝 BaseAdapter:讓 ListView 寫出 RecyclerView 的手感
雖然新專案大多已經轉向 RecyclerView,但在不少場景下,ListView 與 GridView 依然是更直接的選擇,而選擇它們也就意味著要寫更多 Adapter
Android 自定義日曆控件實作全過程詳解
一、為什麼要自定義控件 有時候原生控件在外觀或功能上無法滿足需求,這時可以透過自定義控件來定制;還有一種情況是,原生控件雖然能透過繁瑣的程式碼勉強實現目標,但用自定義控件
Android UI 元件系列:GridView 網格版面配置
GridView 以列與行的方式排列內容,適合顯示圖示、圖片等元素,核心在於設定 Adapter。這裡主要會用到 BaseAdapter 類別,重寫其中的方法,重點是重寫