本篇文章為大家展示了Android中怎么利用OKHTTP實現(xiàn)單例,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
創(chuàng)新互聯(lián)長期為上1000家客戶提供的網(wǎng)站建設(shè)服務,團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為圍場企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計、成都做網(wǎng)站,圍場網(wǎng)站改版等技術(shù)服務。擁有10余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
Android OKHTTP的單例和再封裝的實例
public class OkHttpUtil { private static OkHttpClient singleton; //非常有必要,要不此類還是可以被new,但是無法避免反射,好惡心 private OkHttpUtil(){ } public static OkHttpClient getInstance() { if (singleton == null) { synchronized (OkHttpUtil.class) { if (singleton == null) { singleton = new OkHttpClient(); } } } return singleton; } }
之前在看okhttp源碼的時候,發(fā)現(xiàn)square沒有對okhttpclient進行單例,網(wǎng)上也沒找到合適的解釋,以下是自己的猜測
優(yōu)點:使用單例模式,避免了多次創(chuàng)建所產(chǎn)生的垃圾
缺點:對于一些特殊需求的代碼進行一些靈活的配置,單例模式難以實現(xiàn)
總結(jié):做為優(yōu)秀的開源框架,square出發(fā)點是讓用戶更好更靈活的使用和擴展,從用戶角度來說,對于不需要多次配置的項目,可以手動寫一個單例模式,便于內(nèi)存的高效利用
/** * okhttp再次封裝 * Created by zm on 16-2-1 * update by zm on 16-3-19 增加Builder,方便以后內(nèi)容或者字段的擴展 * */ 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) { // 請求加入調(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請求 */ public static void requestGet(final RequestParams req, final Context context, final Handler handler) { // 創(chuàng)建一個Request final Request request = new Request.Builder().url(req.getRequestUrl()).build(); Call call = OkHttpUtil.getInstance().newCall(request); parse(call, handler, req); } /** * post請求 */ public static void requestPost(final RequestParams req, final Context context, final Handler handler) { FormBody.Builder builder = new FormBody.Builder(); //此處是對RequestParams的遍歷,RequestParams類省略 for (Map.EntrymEntry : 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ù)請求的集中管理,方便以后一鍵替換,從get到post */ public static void request(RequestParams req, Context mContext, Handler handler) { // TODO Auto-generated method stub requestGet(req, mContext, handler); } }
最后再奉獻上一個封裝類
/** * * 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對象 * @return */ public staticList getJsonArrayToModel(Message msg, Class t, T model) { // TODO Auto-generated method stub List list = new ArrayList (); 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; } }
上述內(nèi)容就是Android中怎么利用OKHTTP實現(xiàn)單例,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。