編輯:關於 Android 程式設計
隔了一段時間沒寫博客,翻出去年上半年寫的代碼看,設計上確實有不少局限,但基本的通信流程已經跑通了。不知道以後回看現在寫的東西,是不是也會有同樣的感慨。
Android 上實現網絡通信,主流就兩條路:HttpClient 和 HttpURLConnection。下面把兩種實現都封裝一遍,順便做個對比。
把公共的常量、超時配置、請求方式枚舉和抽象方法集中到 AbstractHttp 裡,兩種實現各自繼承即可。
public abstract class AbstractHttp {
/** 默認編碼 */
public static final String DEFAULT_ENCODING = "UTF-8";
/** GET 請求時 url 與參數的分隔符 */
public static final String URL_AND_PARA_SEPARATOR = "?";
/** 是否取消請求 */
protected boolean isCancel = false;
public static final int DEFAULT_BYTE_LENGTH = 8192;
protected static final int LONG_TIME = 0;
protected int connectionTimeOut = LONG_TIME;
protected int soTimeOut = LONG_TIME;
public enum HttpMethod { GET, POST }
public AbstractHttp() { super(); }
public AbstractHttp(int connectionTimeOut, int soTimeOut) {
super();
if (connectionTimeOut < 0 || soTimeOut < 0) {
throw new RuntimeException("connectionTimeOut<0 || soTimeOut<0");
}
if (connectionTimeOut > 0) this.connectionTimeOut = connectionTimeOut;
if (soTimeOut > 0) this.soTimeOut = soTimeOut;
}
/** 取消請求 */
protected void cancel() { isCancel = true; }
/** 異步線程 */
protected void asyncThread(Runnable runnable) { new Thread(runnable).start(); }
/** 異步連接,默認 GET */
public abstract void asyncConnect(String url, HttpCallBack<String> httpCallBack);
public abstract void asyncConnect(String url, Map<String, String> params, HttpCallBack<String> httpCallBack);
public abstract void asyncConnect(String url, Map<String, String> params, HttpMethod httpMethod, HttpCallBack<String> httpCallBack);
/** 同步連接 */
public abstract String syncConnect(String url);
public abstract String syncConnect(String url, Map<String, String> params);
public abstract String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod);
public abstract String syncConnect(String url, Map<String, String> params, HttpCallBack<String> httpCallBack);
public abstract String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod, HttpCallBack<String> httpCallBack);
/** 下載文件 */
public abstract void asyncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack);
public abstract File syncDownloadFile(String url, String fileName);
public abstract File syncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack);
}
回調覆蓋了請求生命週期中的所有節點:開始、加載進度、成功、失敗、取消。
public interface HttpCallBack<T> {
void onStart(String url);
void onLoading(long progress, long count);
void onSuccess(T t);
void onFailure(String error, Throwable e);
void onCancel();
}
再派生出兩個特化版本,讓業務方不用關心泛型細節:
public abstract class HttpConnectCallBack implements HttpCallBack<String> {
@Override public abstract void onSuccess(String content);
}
public abstract class HttpDownloadCallBack implements HttpCallBack<File> {
@Override public abstract void onSuccess(File file);
}
關鍵點在 getHttpClient():通過 SchemeRegistry 同時註冊 http 與 https,並用 ThreadSafeClientConnManager 支持線程安全的連接池;請求對象的構造交給 getHttpUriRequest(),POST 時把 Map 轉成 UrlEncodedFormEntity,GET 時則用 URLEncodedUtils 把參數拼到 URL 後面。
public class Http extends AbstractHttp {
public Http() { super(); }
public Http(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); }
private HttpClient getHttpClient() {
HttpParams httpParams = new BasicHttpParams();
if (connectionTimeOut != LONG_TIME && soTimeOut != LONG_TIME) {
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParams, soTimeOut);
}
HttpConnectionParams.setTcpNoDelay(httpParams, true);
HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_BYTE_LENGTH);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
return new DefaultHttpClient(manager, httpParams);
}
private HttpUriRequest getHttpUriRequest(String url, HttpMethod httpMethod, Map<String, String> params) {
if (HttpMethod.POST == httpMethod) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(list, DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) { }
}
return httpPost;
} else {
if (params != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
url += URL_AND_PARA_SEPARATOR;
url += URLEncodedUtils.format(list, DEFAULT_ENCODING);
}
return new HttpGet(url);
}
}
@Override
public void asyncConnect(final String url, final Map<String, String> params,
final HttpMethod httpMethod, final HttpCallBack<String> httpCallBack) {
asyncThread(new Runnable() {
@Override public void run() {
syncConnect(url, params, httpMethod, httpCallBack);
}
});
}
@Override
public String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod,
HttpCallBack<String> httpCallBack) {
if (TextUtils.isEmpty(url)) return null;
BufferedReader reader = null;
HttpClient httpClient = null;
int statusCode = -1;
try {
if (httpCallBack != null) httpCallBack.onStart(url);
HttpUriRequest request = getHttpUriRequest(url, httpMethod, params);
httpClient = getHttpClient();
HttpResponse httpResponse = httpClient.execute(request);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = null;
long progress = 0;
long count = httpResponse.getEntity().getContentLength();
isCancel = false;
if (httpCallBack != null && count != -1) httpCallBack.onLoading(progress, count);
while ((!isCancel) && (line = reader.readLine()) != null) {
buffer.append(line);
if (httpCallBack != null && count != -1) {
progress += line.getBytes().length;
httpCallBack.onLoading(progress, count);
}
}
if (httpCallBack != null) {
if (!isCancel) {
httpCallBack.onLoading(count, count);
} else {
reader.close();
httpCallBack.onCancel();
return null;
}
}
reader.close();
if (httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString());
return buffer.toString();
} else {
if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null);
}
} catch (Exception e) {
if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e);
} finally {
if (httpClient != null) httpClient.getConnectionManager().shutdown();
}
return null;
}
@Override
public File syncDownloadFile(String url, String fileName, HttpCallBack<File> httpDownloadCallBack) {
// 與 syncConnect 結構一致,差別在於把響應流寫入 FileOutputStream,
// 並用 1 秒的時間閾值控制 onLoading 的回調頻率,避免刷新過於頻繁
return null;
}
}
異步方法只是把同步邏輯包一層線程,同步方法才是真正幹活的地方,這樣設計的好處是同一套核心邏輯能同時支持兩種調用方式。下載文件時,進度回調做了節流處理:每累積 1 秒才回報一次,避免頻繁觸發 UI 刷新。
接口完全一致,只是內部換成 JDK 原生的連接類。核心在 getHttpURLConnection():GET 把參數拼到 URL,POST 則設置 doOutput 並寫入輸出流。
public class KingHttp extends AbstractHttp {
public KingHttp() { super(); }
public KingHttp(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); }
private HttpURLConnection getHttpURLConnection(String url, HttpMethod httpMethod,
Map<String, String> params) throws IOException {
String paras = null;
if (params != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
paras = URLEncodedUtils.format(list, DEFAULT_ENCODING);
}
if (HttpMethod.GET == httpMethod && paras != null) {
url += URL_AND_PARA_SEPARATOR;
url += paras;
}
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setConnectTimeout(connectionTimeOut);
httpURLConnection.setReadTimeout(soTimeOut);
httpURLConnection.setUseCaches(false);
if (HttpMethod.POST == httpMethod) {
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
if (paras != null) httpURLConnection.getOutputStream().write(paras.getBytes());
} else {
httpURLConnection.setRequestMethod("GET");
}
return httpURLConnection;
}
@Override
public String syncConnect(String url, Map<String, String> params, HttpMethod httpMethod,
HttpCallBack<String> httpCallBack) {
if (TextUtils.isEmpty(url)) return null;
BufferedReader reader = null;
HttpURLConnection conn = null;
int statusCode = -1;
try {
if (httpCallBack != null) httpCallBack.onStart(url);
conn = getHttpURLConnection(url, httpMethod, params);
conn.connect();
statusCode = conn.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
String line = null;
long progress = 0;
long count = conn.getContentLength();
isCancel = false;
while ((!isCancel) && (line = reader.readLine()) != null) {
buffer.append(line);
if (httpCallBack != null && count != -1) {
progress += line.getBytes().length;
httpCallBack.onLoading(progress, count);
}
}
reader.close();
if (httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString());
return buffer.toString();
} else {
if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null);
}
} catch (Exception e) {
if (httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e);
} finally {
if (conn != null) conn.disconnect();
}
return null;
}
}
HttpClient 的優勢是 API 完備、連接池管理成熟,適合需要大量並發請求、需要精細控制連接行為的場景;缺點是它已被 Google 標記為不再維護,Android 6.0 之後需要自行引入 jar 包。
HttpURLConnection 是官方推薦的方案,在 Android 上做了針對性的優化(例如與內建的 HTTP 連接池、響應緩存配合更好),代碼也更精簡。新項目直接用它即可。
無論選哪種,封裝思路是一致的:抽象基類定接口 → 具體實現換内核 → 回調接口對外暴露結果,這樣上層業務完全不依賴具體的網絡庫。
Android Studio 中正確引入 jar 包的完整步驟
很多新手在 Android Studio 裏引入 jar 包時總是磕磕絆絆,稍不注意就導致引用失敗。下面用幾張圖把正確的操作流程講清楚。 1. 首先,找到你需要的 jar
Android 5.0 材料設計抽屜旋轉菜單實作詳解
先看效果: 這是 Android 5.0 推出「材料設計」之後的標準 UI 呈現,左上方漢堡按鈕點擊後側邊菜單滑出,同時左上角圖示會跟著旋轉。以前一直沒仔細研究,寫篇文
Android 表情面板實作:emoji 表情的展示與文字顯示完整教學
前言 在 Android 專案中,只要牽涉到社交類的功能,幾乎都少不了表情。這裡使用的表情是 emoji,於是在完成之後,筆者特地做了一個 demo 來分享,主要示範表情
一鍵 root 失敗了怎麼辦?改用刷入 Root 包應急
如果手機無法透過刷機精靈「實用工具」中的「Root 解鎖」取得權限,可以改走卡刷 Root 包這條路。本方案適用於多數帶 Bootloader 的機型,例如 HTC、Go