編輯:關於 Android 程式設計
Android 6.0 把 Apache HTTP Client 的所有包與類都標記為 deprecated,不再建議使用,所有跟 HTTP 相關的數據請求與提交操作都改用 HttpURLConnection 類實現。然而很多開發者一直習慣用 Apache HTTP Client 做 Android 客戶端與後台 HTTP 介面的數據交互。
本人剛用 HttpURLConnection 做了一個 Android App,不小心踩了幾個坑,這裡總結最常用的幾種用法:透過 HttpURLConnection 來 POST 提交 JSON 數據、GET 請求 JSON 數據,以及下載圖片(分顯示進度與不顯示進度兩種)。其中提交數據時,涉及中文一定要先把中文轉碼成 UTF-8 之後再 POST 提交,否則就會一直遇到 HTTP 400 的錯誤。
public UserDto execute(String... params) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try { // read responseURLEncoder.encode(para, "GBK"); String urlWithParams = DOMAIN_ADDRESS + MEMBER_REQUEST_TOKEN_URL + "?userName=" + java.net.URLEncoder.encode(params[0],"utf-8") + "&password=" + params[1]; URL url = new URL(urlWithParams); urlConnection = (HttpURLConnection) url.openConnection(); /* optional request header */ urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); /* optional request header */ urlConnection.setRequestProperty("Accept", "application/json"); /* for Get request */ urlConnection.setRequestMethod("GET"); int statusCode = urlConnection.getResponseCode(); /* 200 represents HTTP OK */ if (statusCode == 200) { inputStream = new BufferedInputStream(urlConnection.getInputStream()); String response = HttpUtil.convertInputStreamToString(inputStream); Gson gson = new Gson(); UserDto dto = gson.fromJson(response, UserDto.class); if (dto != null && dto.getToken() != null) { Log.i("token", "find the token = " + dto.getToken()); } return dto; } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } } return null; } public Mapexecute(NotificationDto dto) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try { URL url = new URL(getUrl); urlConnection = (HttpURLConnection) url.openConnection(); /* optional request header */ urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); /* optional request header */ urlConnection.setRequestProperty("Accept", "application/json"); dto.setCreator(java.net.URLEncoder.encode(dto.getCreator(), "utf-8")); // read response /* for Get request */ urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); Gson gson = new Gson(); String jsonString = gson.toJson(dto); wr.writeBytes(jsonString); wr.flush(); wr.close(); // try to get response int statusCode = urlConnection.getResponseCode(); if (statusCode == 200) { inputStream = new BufferedInputStream(urlConnection.getInputStream()); String response = HttpUtil.convertInputStreamToString(inputStream); Map resultMap = gson.fromJson(response, Map.class); if (resultMap != null && resultMap.size() > 0) { Log.i("applyDesigner", "please check the map with key"); } return resultMap; } } catch(Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } } return null; }
package com.example.demo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.util.Log; public class ImageLoadTask extends AsyncTask{ private Handler handler; public ImageLoadTask(Handler handler) { this.handler = handler; } protected void onPostExecute(Bitmap result) { Message msg = new Message(); msg.obj = result; handler.sendMessage(msg); } protected Bitmap doInBackground(String... getUrls) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try { // open connection URL url = new URL(getUrls[0]); urlConnection = (HttpURLConnection) url.openConnection(); /* for Get request */ urlConnection.setRequestMethod("GET"); int fileLength = urlConnection.getContentLength(); int statusCode = urlConnection.getResponseCode(); if (statusCode == 200) { inputStream = urlConnection.getInputStream(); byte data[] = new byte[4096]; long total = 0; int count; ByteArrayOutputStream output = new ByteArrayOutputStream(); while ((count = inputStream.read(data)) != -1) { total += count; // publishing the progress.... if (fileLength > 0 && handler != null) { handler.sendEmptyMessage(((int) (total * 100 / fileLength)) - 1); } output.write(data, 0, count); } ByteArrayInputStream bufferInput = new ByteArrayInputStream(output.toByteArray()); Bitmap bitmap = BitmapFactory.decodeStream(bufferInput); inputStream.close(); bufferInput.close(); output.close(); Log.i("image", "already get the image by uuid : " + getUrls[0]); handler.sendEmptyMessage(100); return bitmap; } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } } return null; } }
使用 HttpURLConnection 提交 JSON 數據時,編碼方式為 UTF-8;所有中文字符請務必預先轉碼為 UTF-8,然後在後台伺服器對應的 API 中解碼為 UTF-8,否則就會報 HTTP 400 錯誤。
Android 效能優化(下):記憶體管理、Bitmap 優化與 TraceView 分析
記憶體與 Android 應用記憶體效率是應用效能的重要指標。Android 為每個應用提供沙箱機制與記憶體上限,當記憶體不足時,系統可能觸發 low memory ki
仿微信底部 Tab:讓高亮 indicator 黏著手指一起滑
微信首頁分成三個 Tab,被選中的那一格下方會有一條高亮的長條 indicator。有意思的是,切換頁面時它並不是等動畫結束才「跳」到新位置,而是隨著 ViewPager
Android 在 Eclipse 中進行單元測試:Activity 與 Class 測試
在 Android 專案中,單元測試可以幫助開發者快速驗證局部功能,而不必每次都重新執行整個應用。尤其是在 Eclipse 時代,透過 Instrumentation T
Android 做出圓角邊框對話框的方法
前言 設計稿給了一個圓角邊框的對話框,查了網上不少寫法都大同小異。這裡提供另一個思路——用 layer-list 把「邊框色塊」與「內容色塊」疊起來,藉由內縮的 padd