Android 的OkHttp 網路請求框架的學習封裝
自述:在此以前,自己從來沒有寫過部落格,今天是第一次寫,真心是有點小激動,正要下筆卻不知道應該從何說起,若是寫的不好,請各位見諒吧!關於網路請求,我自認為自己是一個菜鳥,沒有任何經驗,之前做的專案都是別人封裝好,告訴我怎麼呼叫就好了。至於怎麼封裝邏輯的,真是一竅不通,可近來比較閒,就學習封裝了一下OkHttp 。
OkHttp 分為同步和非同步請求;請求方式常用的有 get和post兩種方式,封裝請求的大致步驟為:
1、首先 建立 一個mOkHttpClient = new OkHttpClient()物件;
2、構建Request請求物件(根據get和post不同的請求方式分別建立);
3、如果是 post請求還需要 構建 請求引數 Params,RequestBody requestBody = buildFormData(params); builder.post(requestBody).build;;
4、進行網路非同步請求 mOkHttpClient.newCall(request).enqueue(new Callback() {} ),如果是同步請求,則改為 Response response = mOkHttpClient.newCall(request).execute()進行 ;
具體實現就不細說了,直接上程式碼如下:
其中的 BaseCallBack回撥機制封裝如下:public class OkHttpManager { private static OkHttpManager mOkHttpManager; private OkHttpClient mOkHttpClient; private Gson mGson; private Handler handler; private OkHttpManager() { mOkHttpClient = new OkHttpClient(); mOkHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS); mGson = new Gson(); handler = new Handler(Looper.getMainLooper()); } //建立 單例模式(OkHttp官方建議如此操作) public static OkHttpManager getInstance() { if (mOkHttpManager == null) { mOkHttpManager = new OkHttpManager(); } return mOkHttpManager; } /*********************** * 對外公佈的可調方法 ************************/ public void getRequest(String url, final BaseCallBack callBack) { Request request = buildRequest(url, null, HttpMethodType.GET); doRequest(request, callBack); } public void postRequest(String url, final BaseCallBack callBack, Map<String, String> params) { Request request = buildRequest(url, params, HttpMethodType.POST); doRequest(request, callBack); } public void postUploadSingleImage(String url, final BaseCallBack callback, File file, String fileKey, Map<String, String> params) { Param[] paramsArr = fromMapToParams(params); try { postAsyn(url, callback, file, fileKey, paramsArr); } catch (IOException e) { e.printStackTrace(); } } public void postUploadMoreImages(String url, final BaseCallBack callback, File[] files, String[] fileKeys, Map<String, String> params) { Param[] paramsArr = fromMapToParams(params); try { postAsyn(url, callback, files, fileKeys, paramsArr); } catch (IOException e) { e.printStackTrace(); } } /*********************** * 對內方法 ************************/ //單個檔案上傳請求 不帶引數 private void postAsyn(String url, BaseCallBack callback, File file, String fileKey) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null); doRequest(request, callback); } //單個檔案上傳請求 帶引數 private void postAsyn(String url, BaseCallBack callback, File file, String fileKey, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params); doRequest(request, callback); } //多個檔案上傳請求 帶引數 private void postAsyn(String url, BaseCallBack callback, File[] files, String[] fileKeys, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, params); doRequest(request, callback); } //非同步下載檔案 public void asynDownloadFile(final String url, final String destFileDir, final BaseCallBack callBack) { final Request request = buildRequest(url, null, HttpMethodType.GET); callBack.OnRequestBefore(request); //提示載入框 mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callBack.onFailure(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { // callBack.onResponse(response); InputStream is = null; byte[] buf = new byte[1024*2]; final long fileLength = response.body().contentLength(); int len = 0; long readLength = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); readLength += len; int curProgress = (int) (((float) readLength / fileLength) * 100); Log.e("lgz", "onResponse: >>>>>>>>>>>>>" + curProgress + ", readLength = " + readLength + ", fileLength = " + fileLength); callBack.inProgress(curProgress, fileLength, 0); } fos.flush(); //如果下載檔案成功,第一個引數為檔案的絕對路徑 callBackSuccess(callBack, call, response, file.getAbsolutePath()); } catch (IOException e) { callBackError(callBack, call, response.code()); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } //構造上傳圖片 Request private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) { params = validateParam(params); MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (Param param : params) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(MediaType.parse("image/png"), param.value)); } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); //TODO 根據檔名設定contentType builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody); } } RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); } //Activity頁面所有的請求以Activity物件作為tag,可以在onDestory()裡面統一取消,this public void cancelTag(Object tag) { for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } private String guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } private String getFileName(String path) { int separatorIndex = path.lastIndexOf("/"); return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length()); } private Param[] fromMapToParams(Map<String, String> params) { if (params == null) return new Param[0]; int size = params.size(); Param[] res = new Param[size]; Set<Map.Entry<String, String>> entries = params.entrySet(); int i = 0; for (Map.Entry<String, String> entry : entries) { res[i++] = new Param(entry.getKey(), entry.getValue()); } return res; } //去進行網路 非同步 請求 private void doRequest(Request request, final BaseCallBack callBack) { callBack.OnRequestBefore(request); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callBack.onFailure(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { callBack.onResponse(response); String result = response.body().string(); if (response.isSuccessful()) { if (callBack.mType == String.class) { // callBack.onSuccess(call, response, result); callBackSuccess(callBack, call, response, result); } else { try { Object object = mGson.fromJson(result, callBack.mType);//自動轉化為 泛型物件 // callBack.onSuccess(call, response, object); callBackSuccess(callBack, call, response, object); } catch (JsonParseException e) { //json解析錯誤時呼叫 callBack.onEror(call, response.code(), e); } } } else { callBack.onEror(call, response.code(), null); } } }); } //建立 Request物件 private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) { Request.Builder builder = new Request.Builder(); builder.url(url); if (methodType == HttpMethodType.GET) { builder.get(); } else if (methodType == HttpMethodType.POST) { RequestBody requestBody = buildFormData(params); builder.post(requestBody); } return builder.build(); } //構建請求所需的引數表單 private RequestBody buildFormData(Map<String, String> params) { FormBody.Builder builder = new FormBody.Builder(); builder.add("platform", "android"); builder.add("version", "1.0"); builder.add("key", "123456"); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } } return builder.build(); } private void callBackSuccess(final BaseCallBack callBack, final Call call, final Response response, final Object object) { handler.post(new Runnable() { @Override public void run() { callBack.onSuccess(call, response, object); } }); } private void callBackError(final BaseCallBack callBack, final Call call, final int code) { handler.post(new Runnable() { @Override public void run() { callBack.onEror(call, code, null); } }); } private Param[] validateParam(Param[] params) { if (params == null) return new Param[0]; else return params; } public static class Param { public Param() { } public Param(String key, String value) { this.key = key; this.value = value; } String key; String value; } enum HttpMethodType { GET, POST } }
public abstract class BaseCallBack<T> { public Type mType; static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } ParameterizedType parameterized = (ParameterizedType) superclass; return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); } public BaseCallBack() { mType = getSuperclassTypeParameter(getClass()); } protected abstract void OnRequestBefore(Request request); protected abstract void onFailure(Call call, IOException e); protected abstract void onSuccess(Call call, Response response, T t); protected abstract void onResponse(Response response); protected abstract void onEror(Call call, int statusCode, Exception e); protected abstract void inProgress(int progress, long total , int id); }
上面這個類OkHttpManager 是我根據網路上各家資源學習封裝好的,copy進程式碼可以直接使用,並且根據okhttp3.0以後的版本,對之前的一下請求引數設定進行了最新的修改,具體如下:
1、設定請求超時引數;
okhttp3.0以前的版本是這樣設定的
new OkHttpClient();
mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);
之後的版本是這樣設定的:
new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//設定讀取超時時間
.writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//設定寫的超時時間
.connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//設定連線超時時間
2、post方式請求時,構建表單物件引數;
okhttp3.0以前的版本是這樣構建的:new FormEncodingBuilder()物件,然後向裡面add (key,value)引數;
之後的版本更改為:FormBody body = new FormBody.Builder(),.add(key, value);即是FormEncodingBuilder已被FormBody取代;
至於BaseCallBack類,根據請求資料的功能的不同,還需要對此進行封裝,整合自己需要的方法實現;
一、進行一般的資料載入請求,可直接呼叫如下:
模擬使用者登入:
Map<String, String> params = new HashMap<String, String>();
params.put("Mobile", username.getText().toString());
params.put("PassWord", password.getText().toString());
OkHttpManager.getInstance().postRequest(Constants.LOGIN_URL, new LoadCallBack<String>(getActivity()) {
@Override
protected void onSuccess(Call call, Response response, String s) {
Log.e("lgz", "onSuccess = " + s);
Toast.makeText(getActivity(), "登入成功!", Toast.LENGTH_LONG).show();
}
@Override
protected void onEror(Call call, int statusCode, Exception e) {
Log.e("lgz", "Exception = " + e.toString());
}
}
, params);
上面登入請求中 就用到了自己根據需要再次封裝的Callback類的繼承實現,LoadCallBack<T>類:
//新增對請求時對話方塊的處理
public abstract class LoadCallBack<T> extends BaseCallBack<T> {
private Context context;
private SpotsDialog spotsDialog;
public LoadCallBack(Context context) {
this.context = context;
spotsDialog = new SpotsDialog(context);
}
private void showDialog() {
spotsDialog.show();
}
private void hideDialog() {
if (spotsDialog != null) {
spotsDialog.dismiss();
}
}
public void setMsg(String str) {
spotsDialog.setMessage(str);
}
public void setMsg(int resId) {
spotsDialog.setMessage(context.getString(resId));
}
@Override
protected void OnRequestBefore(Request request) {
showDialog();
}
@Override
protected void onFailure(Call call, IOException e) {
hideDialog();
}
@Override
protected void onResponse(Response response) {
hideDialog();
}
@Override
protected void inProgress(int progress, long total, int id) {
}
其實這個類就是對BaseCallBack再次繼承實現;
二、下載檔案,並顯示進度條對話方塊的請求操作:
下載一張圖片:
OkHttpManager.getInstance().asynDownloadFile("http://www.7mlzg.com/uploads/bwf_1477419976.jpg", FILE_PATH, new FileCallBack<String>(getActivity()) {
@Override
protected void onResponse(Response response) {
}
@Override
protected void onSuccess(Call call, Response response, String s) {
super.onSuccess(call, response, s);
Log.e("lgz", "status = : " + s);
Toast.makeText(getActivity(), "下載成功", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File(s));//廣播通知系統圖集更新
intent.setData(uri);
getActivity().sendBroadcast(intent);
}
});
上面下載圖片中,就用到了自己根據需要再次繼承Callback類封裝得到的FileCallBack<T>類如下:
public abstract class FileCallBack<T> extends BaseCallBack<T> {
private Context mContext;
private ProgressDialog mProgressDialog;
public FileCallBack(Context context) {
mContext = context;
initDialog();
}
private void initDialog(){
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle("下載中...");
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMax(100);
}
private void hideDialog() {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
@Override
protected void OnRequestBefore(Request request) {
mProgressDialog.show();
}
@Override
protected void onFailure(Call call, IOException e) {
hideDialog();
}
@Override
protected void onSuccess(Call call, Response response, T t) {
Log.e("lgz", "onSuccess: >>>>>>>>>>>>>");
hideDialog();
}
@Override
protected void onEror(Call call, int statusCode, Exception e) {
hideDialog();
}
@Override
protected void inProgress(int progress, long total, int id) {
Log.e("lgz", "inProgress: >>>>>>>>>>>>>"+progress);
mProgressDialog.setProgress(progress);
}
}
三、最後說一下使用okhttp的配置:
在Android Studio 中,直接在build.gradle檔案裡配置 :compile 'com.squareup.okhttp3:okhttp:3.4.1'
在Eclipse裡需要匯入jar包使用,下載最新jar;
當然了,這裡只是對Okhttp常用的一些功能進行了封裝處理,使用的都是非同步請求方式,至於同步操作,我個人覺得不是很常用,使用時需要開啟一個執行緒,不然會阻塞UI執行緒的;最後,這只是一個簡單的學習,其中要是有不足和錯誤,還希望大家留言批評指正,謝謝!