Android OKHTTP的單例和再封裝的實(shí)例
Android OKHTTP的單例和再封裝的實(shí)例
/** * Created by zm on 16-2-1 * okhttp的再封裝,對(duì)于2.x版本,3.x版本將原有對(duì)okhttpclient配置 * 改成了builder模式配 * 置,對(duì)于超時(shí)、代理、dns,okhttp已經(jīng)做好了配置, * 若不需要特殊配置,可以跳過(guò) */ public class OkHttpUtil { private static OkHttpClient singleton; //非常有必要,要不此類還是可以被new,但是無(wú)法避免反射,好惡心 private OkHttpUtil(){ } public static OkHttpClient getInstance() { if (singleton == null) { synchronized (OkHttpUtil.class) { if (singleton == null) { singleton = new OkHttpClient(); } } } return singleton; } }
之前在看okhttp源碼的時(shí)候,發(fā)現(xiàn)square沒(méi)有對(duì)okhttpclient進(jìn)行單例,網(wǎng)上也沒(méi)找到合適的解釋,以下是自己的猜測(cè)
優(yōu)點(diǎn):使用單例模式,避免了多次創(chuàng)建所產(chǎn)生的垃圾
缺點(diǎn):對(duì)于一些特殊需求的代碼進(jìn)行一些靈活的配置,單例模式難以實(shí)現(xiàn)
總結(jié):做為優(yōu)秀的開源框架,square出發(fā)點(diǎn)是讓用戶更好更靈活的使用和擴(kuò)展,從用戶角度來(lái)說(shuō),對(duì)于不需要多次配置的項(xiàng)目,可以手動(dòng)寫一個(gè)單例模式,便于內(nèi)存的高效利用
/** * okhttp再次封裝 * Created by zm on 16-2-1 * update by zm on 16-3-19 增加Builder,方便以后內(nèi)容或者字段的擴(kuò)展 * */ public class HttpTools { private Context context; private final RequestParams req; private final Handler handler; public HttpTools(Builder builder) { // TODO Auto-generated constructor stub context = builder.context; req = builder.req; handler = builder.handler; } public static class Builder { private final RequestParams req; private final Context context; private final Handler handler; public Builder(RequestParams req, Context mContext, Handler handler) { // TODO Auto-generated constructor stub this.req = req; this.context = mContext; this.handler = handler; } public HttpTools build() { return new HttpTools(this); } } public void requestBuilder() { // TODO Auto-generated method stub if(req==null||context==null||handler==null){ throw new NullPointerException("NullPointerException"); } requestGet(req, context, handler); } private static void parse(Call call, final Handler handler, final RequestParams req) { // 請(qǐng)求加入調(diào)度 call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { // TODO Auto-generated method stub String result = response.body().string(); if (result != null) { Message message = Message.obtain(); message.obj = result; message.what = req.getSuccessMsgWhat(); handler.sendMessage(message); } } @Override public void onFailure(Call call, IOException e) { // TODO Auto-generated method stub handler.sendEmptyMessage(req.getFailMsgWhat()); } }); } /** * * @param req * @param context * @param handler * * get請(qǐng)求 */ public static void requestGet(final RequestParams req, final Context context, final Handler handler) { // 創(chuàng)建一個(gè)Request final Request request = new Request.Builder().url(req.getRequestUrl()).build(); Call call = OkHttpUtil.getInstance().newCall(request); parse(call, handler, req); } /** * post請(qǐng)求 */ public static void requestPost(final RequestParams req, final Context context, final Handler handler) { FormBody.Builder builder = new FormBody.Builder(); //此處是對(duì)RequestParams的遍歷,RequestParams類省略 for (Map.Entry<String, Object> mEntry : req.getParamEntry()) { String mEntryKey = mEntry.getKey(); Object mEntryValue = mEntry.getValue(); if (TextUtils.isEmpty(mEntryKey)) { continue; } builder.add(mEntryKey, mEntryValue.toString()); } RequestBody body = builder.build(); Request request = new Request.Builder().url(req.getUrl()).post(body).build(); Call call = OkHttpUtil.getInstance().newCall(request); parse(call, handler, req); } /** * 數(shù)據(jù)請(qǐng)求的集中管理,方便以后一鍵替換,從get到post */ public static void request(RequestParams req, Context mContext, Handler handler) { // TODO Auto-generated method stub requestGet(req, mContext, handler); } }
最后再奉獻(xiàn)上一個(gè)封裝類
/** * * Created by zm on 16-2-1 * 基于Gson的json轉(zhuǎn)model封裝類 * */ public class JsonToModel { private static String info = "info"; public static String getInfo() { return info; } public static void setInfo(String info) { JsonToModel.info = info; } /** * * @param msg * @param t * model類 * @param model * model對(duì)象 * @return */ public static <T> List<T> getJsonArrayToModel(Message msg, Class<T> t, T model) { // TODO Auto-generated method stub List<T> list = new ArrayList<T>(); try { JSONObject json = new JSONObject(msg.obj.toString()); for (int i = 0; i < json.getJSONArray(getInfo()).length(); i++) { model = GsonHelper.toType(json.getJSONArray(getInfo()).get(i).toString(), t); list.add(model); } return list; } catch (Exception e) { // TODO Auto-generated catch block Log.e("getJsonArrayToModel", "error"); e.printStackTrace(); } return null; } }
json轉(zhuǎn)model的這個(gè)類中,當(dāng)時(shí)沒(méi)考慮到過(guò)多性能的問(wèn)題,在此類中即使用了org.json.JSONObject也使用了gson,此處還可以做出相應(yīng)的優(yōu)化
如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
- Android使用OKHttp庫(kù)實(shí)現(xiàn)視頻文件的上傳到服務(wù)器功能
- Android Okhttp請(qǐng)求查詢購(gòu)物車的實(shí)例代碼
- Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實(shí)例
- android 開發(fā)中使用okhttp上傳文件到服務(wù)器
- Android okhttp3.0忽略https證書的方法
- Android使用OkHttp請(qǐng)求自簽名的https網(wǎng)站的示例
- Android中okhttp3使用詳解
- android通過(guò)okhttpClient下載網(wǎng)頁(yè)內(nèi)容的實(shí)例代碼
- Android開發(fā)之OkHttpUtils的具體使用方法
- Android中實(shí)現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度
- android中實(shí)現(xiàn)OkHttp下載文件并帶進(jìn)度條
- Android使用OKHTTP解析JSON數(shù)據(jù)的實(shí)例代碼
- Android使用OkHttp上傳圖片的實(shí)例代碼
- Android OkHttp 結(jié)合php 多圖片上傳實(shí)例
- 詳解Android中OkHttp3的例子和在子線程更新UI線程的方法
- android Retrofit2+okHttp3使用總結(jié)
- Android OkHttp Post上傳文件并且攜帶參數(shù)實(shí)例詳解
- Android OkHttp基本使用詳解
相關(guān)文章
android在連拍菜單中增加連拍張數(shù)選項(xiàng)功能實(shí)現(xiàn)代碼
想要增加連拍張數(shù)選項(xiàng)需要在entries, entryvalues中添加兩項(xiàng),同時(shí)在mtk_strings.xml中添加相應(yīng)的字符串,具體如下,感興趣的朋友可以參考下哈2013-06-06Android藍(lán)牙通信之搜索藍(lán)牙設(shè)備
這篇文章主要介紹了Android藍(lán)牙通信之搜索藍(lán)牙設(shè)備,需要的朋友可以參考下2017-09-09Android中自定義view實(shí)現(xiàn)側(cè)滑效果
這篇文章主要介紹了Android中自定義view實(shí)現(xiàn)側(cè)滑效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11淺析AndroidStudio3.0最新 Android Profiler分析器(cpu memory network
Android Profiler分為三大模塊: cpu、內(nèi)存 、網(wǎng)絡(luò)。本文給大家介紹AndroidStudio3.0最新 Android Profiler分析器(cpu memory network 分析器)的相關(guān)知識(shí),他們的基本使用方法,在文中都給大家提到,具體內(nèi)容詳情大家通過(guò)本文一起學(xué)習(xí)吧2017-12-12超簡(jiǎn)單實(shí)現(xiàn)Android自定義Toast示例(附源碼)
本篇文章主要介紹了超簡(jiǎn)單實(shí)現(xiàn)Android自定義Toast示例(附源碼),具有一定的參考價(jià)值,有興趣的可以了解一下。2017-02-02Android HttpClient GET或者POST請(qǐng)求基本使用方法
在Android開發(fā)中我們經(jīng)常會(huì)用到網(wǎng)絡(luò)連接功能與服務(wù)器進(jìn)行數(shù)據(jù)的交互,為此Android的SDK提供了Apache的HttpClient來(lái)方便我們使用各種Http服務(wù).這里只介紹如何使用HttpClient發(fā)起GET或者POST請(qǐng)求2012-12-12Android使用Handler實(shí)現(xiàn)定時(shí)器與倒計(jì)時(shí)器功能
Handler的最常見(jiàn)應(yīng)用場(chǎng)景之一便是通過(guò)Handler在子線程中間接更新UI。這篇文章主要介紹了Android使用Handler實(shí)現(xiàn)定時(shí)器與倒計(jì)時(shí)器功能,需要的朋友可以參考下2018-02-02Android編程實(shí)現(xiàn)啟動(dòng)界面的方法分析
這篇文章主要介紹了Android編程實(shí)現(xiàn)啟動(dòng)界面的方法,結(jié)合實(shí)例形式分析了Android啟動(dòng)界面的實(shí)現(xiàn)方法與相關(guān)操作技巧,需要的朋友可以參考下2017-03-03Android開發(fā)教程之ContentProvider數(shù)據(jù)存儲(chǔ)
這篇文章主要介紹了Android開發(fā)教程之ContentProvider數(shù)據(jù)存儲(chǔ)的相關(guān)資料,需要的朋友可以參考下2016-12-12