在上一篇基於retrofit的網絡框架的終極封裝(一)中介紹了頂層api的設計.這裏再沿着代碼走向往裏說.
因爲這裏講的是retrofit的封裝性使用,因此一些retrofit基礎性的使用和配置這裏就不講了.java
全部網絡請求相關的參數和配置所有經過第一層的api和鏈式調用封裝到了ConfigInfo中,最後在start()方法中調用retrofit層,開始網絡請求.git
/** * 在這裏組裝請求,而後發出去 * @param <E> * @return */ @Override public <E> ConfigInfo<E> start(ConfigInfo<E> configInfo) { String url = Tool.appendUrl(configInfo.url, isAppendUrl());//組拼baseUrl和urltail configInfo.url = url; configInfo.listener.url = url; //todo 這裏token還可能在請求頭中,應加上此類狀況的自定義. if (configInfo.isAppendToken){ Tool.addToken(configInfo.params); } if (configInfo.loadingDialog != null && !configInfo.loadingDialog.isShowing()){ try {//預防badtoken最簡便和直接的方法 configInfo.loadingDialog.show(); }catch (Exception e){ } } if (getCache(configInfo)){//異步,去拿緩存--只針對String類型的請求 return configInfo; } T request = generateNewRequest(configInfo);//根據類型生成/執行不一樣的請求對象 /* 這三個方式是給volley預留的 setInfoToRequest(configInfo,request); cacheControl(configInfo,request); addToQunue(request);*/ return configInfo; }
分類生成/執行各種請求:github
private <E> T generateNewRequest(ConfigInfo<E> configInfo) { int requestType = configInfo.type; switch (requestType){ case ConfigInfo.TYPE_STRING: case ConfigInfo.TYPE_JSON: case ConfigInfo.TYPE_JSON_FORMATTED: return newCommonStringRequest(configInfo); case ConfigInfo.TYPE_DOWNLOAD: return newDownloadRequest(configInfo); case ConfigInfo.TYPE_UPLOAD_WITH_PROGRESS: return newUploadRequest(configInfo); default:return null; } }
因此,對retrofit的使用,只要實現如下三個方法就好了:
若是切換到volley或者其餘網絡框架,也是實現這三個方法就行了.json
newCommonStringRequest(configInfo), newDownloadRequest(configInfo); newUploadRequest(configInfo)
@Override protected <E> Call newCommonStringRequest(final ConfigInfo<E> configInfo) { Call<ResponseBody> call; if (configInfo.method == HttpMethod.GET){ call = service.executGet(configInfo.url,configInfo.params); }else if (configInfo.method == HttpMethod.POST){ if(configInfo.paramsAsJson){//參數在請求體以json的形式發出 String jsonStr = MyJson.toJsonStr(configInfo.params); Log.e("dd","jsonstr request:"+jsonStr); RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonStr); call = service.executeJsonPost(configInfo.url,body); }else { call = service.executePost(configInfo.url,configInfo.params); } }else { configInfo.listener.onError("不是get或post方法");//暫時不考慮其餘方法 call = null; return call; } configInfo.tagForCancle = call; call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) { if (!response.isSuccessful()){ configInfo.listener.onCodeError("http錯誤碼爲:"+response.code(),response.message(),response.code()); Tool.dismiss(configInfo.loadingDialog); return; } String string = ""; try { string = response.body().string(); Tool.parseStringByType(string,configInfo); Tool.dismiss(configInfo.loadingDialog); } catch (final IOException e) { e.printStackTrace(); configInfo.listener.onError(e.toString()); Tool.dismiss(configInfo.loadingDialog); } } @Override public void onFailure(Call<ResponseBody> call, final Throwable t) { configInfo.listener.onError(t.toString()); Tool.dismiss(configInfo.loadingDialog); } }); return call; }
既然要封裝,確定就不能用retrofit的常規用法:ApiService接口裏每一個接口文檔上的接口都寫一個方法,而是應該用QueryMap/FieldMap註解,接受一個以Map形式封裝好的鍵值對.這個與咱們上一層的封裝思路和形式都是同樣的.api
@GET() Call<ResponseBody> executGet(@Url String url, @QueryMap Map<String, String> maps); /** * 注意: * 1.若是方法的泛型指定的類不是ResonseBody,retrofit會將返回的string成用json轉換器自動轉換該類的一個對象,轉換不成功就報錯. * 若是不須要gson轉換,那麼就指定泛型爲ResponseBody, * 只能是ResponseBody,子類都不行,同理,下載上傳時,也必須指定泛型爲ResponseBody * 2. map不能爲null,不然該請求不會執行,但能夠size爲空. * 3.使用@url,而不是@Path註解,後者放到方法體上,會強制先urlencode,而後與baseurl拼接,請求沒法成功. * @param url * @param map * @return */ @FormUrlEncoded @POST() Call<ResponseBody> executePost(@Url String url, @FieldMap Map<String, String> map);
/** * 直接post體爲一個json格式時,使用這個方法.注意:@Body 不能與@FormUrlEncoded共存 * @param url * @param body * @return */ @POST() Call<ResponseBody> executeJsonPost(@Url String url, @Body RequestBody body);
retrofit其實有請求時傳入一個javabean的註解方式,確實能夠在框架內部轉換成json.可是不適合封裝.數組
其實很簡單,搞清楚以json形式發出參數的本質: 請求體中的json本質上仍是一個字符串.那麼能夠將Map攜帶過來的參數轉成json字符串,而後用RequestBody包裝一層就行了:緩存
String jsonStr = MyJson.toJsonStr(configInfo.params); RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonStr); call = service.executeJsonPost(configInfo.url,body);
@GET() <T> Call<BaseNetBean<T>> getStandradJson(@Url String url, @QueryMap Map<String, String> maps); //注:BaseNetBean就是三個標準字段的json: public class BaseNetBean<T>{ public int code; public String msg; public T data; }
這樣寫會拋出異常:
報的錯誤服務器
Method return type must not include a type variable or wildcard: retrofit2.Call<T>
JakeWharton的回覆:
You cannot. Type information needs to be fully known at runtime in order for deserialization to work.cookie
由於上面的緣由,咱們只能經過retrofit發請求,返回一個String,本身去解析.但這也有坑:網絡
1.不能寫成下面的形式:
@GET() Call<String> executGet(@Url String url, @QueryMap Map<String, String> maps);
你覺得指定泛型爲String它就返回String,不,你還太年輕了.
這裏的泛型,意思是,使用retrofit內部的json轉換器,將response裏的數據轉換成一個實體類xxx,好比UserBean之類的,而String類明顯不是一個有效的實體bean類,天然轉換失敗.
因此,要讓retrofit不適用內置的json轉換功能,你應該直接指定類型爲ResponseBody:
@GET() Call<ResponseBody> executGet(@Url String url, @QueryMap Map<String, String> maps);
2.既然不採用retrofit內部的json轉換功能,那就要在回調那裏本身拿到字符串,用本身的json解析了.那麼坑又來了:
泛型擦除:
回調接口上指定泛型,在回調方法裏直接拿到泛型,這是在java裏很常見的一個泛型接口設計:
public abstract class MyNetListener<T>{ public abstract void onSuccess(T response,String resonseStr); .... } //使用: call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) { String string = response.body().string(); Gson gson = new Gson(); Type objectType = new TypeToken<T>() {}.getType(); final T bean = gson.fromJson(string,objectType); configInfo.listener.onSuccess(bean,string); ... } ... }
可是,拋出異常:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xxx
這是由於在運行過程當中,經過泛型傳入的類型T丟失了,因此沒法轉換,這叫作泛型擦除:.
要解析的話,仍是老老實實傳入javabean的class吧.因此在最頂層的API裏,有一個必須傳的Class clazz:
postStandardJson(String url, Map map, Class clazz, MyNetListener listener)
綜上,咱們須要傳入class對象,徹底本身去解析json.解析已封裝成方法.也是根據三個不一樣的小類型(字符串,通常json,標準json)
這裏處理緩存時,若是要緩存內容,固然是緩存成功的內容,失敗的就沒必要緩存了.
Tool.parseStringByType(string,configInfo); public static void parseStringByType(final String string, final ConfigInfo configInfo) { switch (configInfo.type){ case ConfigInfo.TYPE_STRING: //緩存 cacheResponse(string, configInfo); //處理結果 configInfo.listener.onSuccess(string, string); break; case ConfigInfo.TYPE_JSON: parseCommonJson(string,configInfo); break; case ConfigInfo.TYPE_JSON_FORMATTED: parseStandJsonStr(string, configInfo); break; } }
json解析框架選擇,gson,fastjson隨意,不過最好也是本身再包一層api:
public static <T> T parseObject(String str,Class<T> clazz){ // return new Gson().fromJson(str,clazz); return JSON.parseObject(str,clazz); }
private static <E> void parseCommonJson( String string, ConfigInfo<E> configInfo) { if (isJsonEmpty(string)){ configInfo.listener.onEmpty(); }else { try{ if (string.startsWith("{")){ E bean = MyJson.parseObject(string,configInfo.clazz); configInfo.listener.onSuccessObj(bean ,string,string,0,""); cacheResponse(string, configInfo); }else if (string.startsWith("[")){ List<E> beans = MyJson.parseArray(string,configInfo.clazz); configInfo.listener.onSuccessArr(beans,string,string,0,""); cacheResponse(string, configInfo); }else { configInfo.listener.onError("不是標準json格式"); } }catch (Exception e){ e.printStackTrace(); configInfo.listener.onError(e.toString()); } } }
三個字段對應的數據直接用jsonObject.optString來取:
JSONObject object = null; try { object = new JSONObject(string); } catch (JSONException e) { e.printStackTrace(); configInfo.listener.onError("json 格式異常"); return; } String key_data = TextUtils.isEmpty(configInfo.key_data) ? NetDefaultConfig.KEY_DATA : configInfo.key_data; String key_code = TextUtils.isEmpty(configInfo.key_code) ? NetDefaultConfig.KEY_CODE : configInfo.key_code; String key_msg = TextUtils.isEmpty(configInfo.key_msg) ? NetDefaultConfig.KEY_MSG : configInfo.key_msg; final String dataStr = object.optString(key_data); final int code = object.optInt(key_code); final String msg = object.optString(key_msg);
注意,optString後字符串爲空的判斷:一個字段爲null時,optString的結果是字符串"null"而不是null
public static boolean isJsonEmpty(String data){ if (TextUtils.isEmpty(data) || "[]".equals(data) || "{}".equals(data) || "null".equals(data)) { return true; } return false; }
而後就是相關的code狀況的處理和回調:
狀態碼爲未登陸時,執行自動登陸的邏輯,自動登陸成功後再重發請求.登陸不成功才執行unlogin()回調.
注意data字段多是一個普通的String,而不是json.
private static <E> void parseStandardJsonObj(final String response, final String data, final int code, final String msg, final ConfigInfo<E> configInfo){ int codeSuccess = configInfo.isCustomCodeSet ? configInfo.code_success : BaseNetBean.CODE_SUCCESS; int codeUnFound = configInfo.isCustomCodeSet ? configInfo.code_unFound : BaseNetBean.CODE_UN_FOUND; int codeUnlogin = configInfo.isCustomCodeSet ? configInfo.code_unlogin : BaseNetBean.CODE_UNLOGIN; if (code == codeSuccess){ if (isJsonEmpty(data)){ if(configInfo.isResponseJsonArray()){ configInfo.listener.onEmpty(); }else { configInfo.listener.onError("數據爲空"); } }else { try{ if (data.startsWith("{")){ final E bean = MyJson.parseObject(data,configInfo.clazz); configInfo.listener.onSuccessObj(bean ,response,data,code,msg); cacheResponse(response, configInfo); }else if (data.startsWith("[")){ final List<E> beans = MyJson.parseArray(data,configInfo.clazz); configInfo.listener.onSuccessArr(beans,response,data,code,msg); cacheResponse(response, configInfo); }else {//若是data的值是一個字符串,而不是標準json,那麼直接返回 if (String.class.equals(configInfo.clazz) ){//此時,E也應該是String類型.若是有誤,會拋出到下面catch裏 configInfo.listener.onSuccess((E) data,data); }else { configInfo.listener.onError("不是標準的json數據"); } } }catch (final Exception e){ e.printStackTrace(); configInfo.listener.onError(e.toString()); return; } } }else if (code == codeUnFound){ configInfo.listener.onUnFound(); }else if (code == codeUnlogin){ //自動登陸 configInfo.client.autoLogin(new MyNetListener() { @Override public void onSuccess(Object response, String resonseStr) { configInfo.client.resend(configInfo); } @Override public void onError(String error) { super.onError(error); configInfo.listener.onUnlogin(); } }); }else { configInfo.listener.onCodeError(msg,"",code); } }
先不考慮多線程下載和斷點續傳的問題,就單單文件下載而言,用retrofit寫仍是挺簡單的
不能像上面字符流類型的請求同樣設置多少s,而應該設爲0,也就是不限時:
OkHttpClient client=httpBuilder.readTimeout(0, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //設置超時
@Streaming //流式下載,不加這個註解的話,會整個文件字節數組所有加載進內存,可能致使oom @GET Call<ResponseBody> download(@Url String fileUrl);
這裏用的是一個異步任務框架,其實用Rxjava更好.
SimpleTask<Boolean> simple = new SimpleTask<Boolean>() { @Override protected Boolean doInBackground() { return writeResponseBodyToDisk(response.body(),configInfo.filePath); } @Override protected void onPostExecute(Boolean result) { Tool.dismiss(configInfo.loadingDialog); if (result){ configInfo.listener.onSuccess(configInfo.filePath,configInfo.filePath); }else { configInfo.listener.onError("文件下載失敗"); } } }; simple.execute();
byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; Log.d("io", "file download: " + fileSizeDownloaded + " of " + fileSize);// 這裏也能夠實現進度監聽 }
1.添加下載時更新進度的攔截器
okHttpClient .addInterceptor(new ProgressInterceptor())
2.ProgressInterceptor:實現Interceptor接口的intercept方法,攔截網絡響應
@Override public Response intercept(Interceptor.Chain chain) throws IOException{ Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(),chain.request().url().toString())).build(); }
3 ProgressResponseBody: 繼承 ResponseBody ,在內部網絡流傳輸過程當中讀取進度:
public class ProgressResponseBody extends ResponseBody { private final ResponseBody responseBody; private BufferedSource bufferedSource; private String url; public ProgressResponseBody(ResponseBody responseBody,String url) { this.responseBody = responseBody; this.url = url; } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } long timePre = 0; long timeNow; private Source source(final Source source) { return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); totalBytesRead += bytesRead != -1 ? bytesRead : 0; timeNow = System.currentTimeMillis(); if (timeNow - timePre > NetDefaultConfig.PROGRESS_INTERMEDIATE || totalBytesRead == responseBody.contentLength()){//至少300ms才更新一次狀態 timePre = timeNow; EventBus.getDefault().post(new ProgressEvent(totalBytesRead,responseBody.contentLength(), totalBytesRead == responseBody.contentLength(),url)); } return bytesRead; } }; } }
通常進度數據用於更新UI,因此最好設置數據傳出的時間間隔,不要太頻繁:
timeNow = System.currentTimeMillis(); if (timeNow - timePre > NetDefaultConfig.PROGRESS_INTERMEDIATE || totalBytesRead == responseBody.contentLength()){//至少300ms才更新一次狀態 timePre = timeNow; EventBus.getDefault().post(new ProgressEvent(totalBytesRead,responseBody.contentLength(), totalBytesRead == responseBody.contentLength(),url)); }
注意: MyNetListener與url綁定,以防止不一樣下載間的進度錯亂.
@Subscribe(threadMode = ThreadMode.MAIN) public void onMessage(ProgressEvent event){ if (event.url.equals(url)){ onProgressChange(event.totalLength,event.totalBytesRead); if (event.done){ unRegistEventBus(); onFinish(); } } }
文件上傳相對於普通post請求有區別,你很是須要了解http文件上傳的協議:
1.提交一個表單,若是包含文件上傳,那麼必須指定類型爲multipart/form-data.這個在retrofit中經過@Multipart註解指定便可.
2.表單中還有其餘鍵值對也要一同傳遞,在retrofit中經過@QueryMap以map形式傳入,這個與普通post請求同樣
3.服務器接收文件的字段名,以及上傳的文件路徑,經過@PartMap以map形式傳入.這裏的字段名對應請求體中Content-Disposition中的name字段的值.大多數服務器默認是file.(由於SSH框架默認的是file?)
4.請求體的content-type用於標識文件的具體MIME類型.在retrofit中,是在構建請求體RequestBody時指定的.須要咱們指定.
那麼如何得到一個文件的MIMe類型呢?讀文件的後綴名的話,不靠譜.最佳方式是讀文件頭,從文件頭中拿到MIME類型.不用擔憂,Android有相關的api的
綜上,相關的封裝以下:
OkHttpClient client=httpBuilder.readTimeout(0, TimeUnit.SECONDS) .connectTimeout(0, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //設置超時
@POST() @Multipart Call<ResponseBody> uploadWithProgress(@Url String url,@QueryMap Map<String, String> options,@PartMap Map<String, RequestBody> fileParameters) ;
這裏的回調就不用開後臺線程了,由於流是在請求體中,而retrofit已經幫咱們搞定了請求過程的後臺執行.
protected Call newUploadRequest(final ConfigInfo configInfo) { if (serviceUpload == null){ initUpload(); } configInfo.listener.registEventBus(); Map<String, RequestBody> requestBodyMap = new HashMap<>(); if (configInfo.files != null && configInfo.files.size() >0){ Map<String,String> files = configInfo.files; int count = files.size(); if (count>0){ Set<Map.Entry<String,String>> set = files.entrySet(); for (Map.Entry<String,String> entry : set){ String key = entry.getKey(); String value = entry.getValue(); File file = new File(value); String type = Tool.getMimeType(file);//拿到文件的實際類型 Log.e("type","mimetype:"+type); UploadFileRequestBody fileRequestBody = new UploadFileRequestBody(file, type,configInfo.url); requestBodyMap.put(key+"\"; filename=\"" + file.getName(), fileRequestBody); } } } Call<ResponseBody> call = service.uploadWithProgress(configInfo.url,configInfo.params,requestBodyMap);
public class UploadFileRequestBody extends RequestBody { private RequestBody mRequestBody; private BufferedSink bufferedSink; private String url; public UploadFileRequestBody(File file,String mimeType,String url) { // this.mRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); this.mRequestBody = RequestBody.create(MediaType.parse(mimeType), file); this.url = url; } @Override public MediaType contentType() { return mRequestBody.contentType(); }
封裝在UploadFileRequestBody中,無需經過okhttp的攔截器實現,由於能夠在構建RequestBody的時候就包裝好(看上面代碼),就不必用攔截器了.
到這裏,主要的請求執行和回調就算講完了,但還有一些,好比緩存控制,登陸狀態的維護,以及cookie管理,請求的取消,gzip壓縮,本地時間校準等等必需的輔助功能的實現和維護,這些將在下一篇文章進行解析.