Android OKHTTP的單例和再封裝的實(shí)例
Android OKHTTP的單例和再封裝的實(shí)例
/**
* Created by zm on 16-2-1
* okhttp的再封裝,對于2.x版本,3.x版本將原有對okhttpclient配置
* 改成了builder模式配
* 置,對于超時(shí)、代理、dns,okhttp已經(jīng)做好了配置,
* 若不需要特殊配置,可以跳過
*/
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源碼的時(shí)候,發(fā)現(xiàn)square沒有對okhttpclient進(jìn)行單例,網(wǎng)上也沒找到合適的解釋,以下是自己的猜測
優(yōu)點(diǎn):使用單例模式,避免了多次創(chuàng)建所產(chǎn)生的垃圾
缺點(diǎn):對于一些特殊需求的代碼進(jìn)行一些靈活的配置,單例模式難以實(shí)現(xiàn)
總結(jié):做為優(yōu)秀的開源框架,square出發(fā)點(diǎn)是讓用戶更好更靈活的使用和擴(kuò)展,從用戶角度來說,對于不需要多次配置的項(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) {
// 請求加入調(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)建一個(gè)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.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ù)請求的集中管理,方便以后一鍵替換,從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對象
* @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í)沒考慮到過多性能的問題,在此類中即使用了org.json.JSONObject也使用了gson,此處還可以做出相應(yīng)的優(yōu)化
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- Android使用OKHttp庫實(shí)現(xiàn)視頻文件的上傳到服務(wù)器功能
- Android Okhttp請求查詢購物車的實(shí)例代碼
- Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實(shí)例
- android 開發(fā)中使用okhttp上傳文件到服務(wù)器
- Android okhttp3.0忽略https證書的方法
- Android使用OkHttp請求自簽名的https網(wǎng)站的示例
- Android中okhttp3使用詳解
- android通過okhttpClient下載網(wǎng)頁內(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筆記之:在ScrollView中嵌套ListView的方法
本篇文章是對Android中在ScrollView中嵌套ListView的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
AndroidStudio kotlin配置詳細(xì)介紹
這篇文章主要介紹了AndroidStudio kotlin配置詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-05-05
詳解Android使用CoordinatorLayout+AppBarLayout實(shí)現(xiàn)拉伸頂部圖片功能
這篇文章主要介紹了Android使用CoordinatorLayout+AppBarLayout實(shí)現(xiàn)拉伸頂部圖片功能,本文實(shí)例文字相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10
Android性能優(yōu)化之利用強(qiáng)大的LeakCanary檢測內(nèi)存泄漏及解決辦法
本篇文章主要介紹了Android性能優(yōu)化之利用LeakCanary檢測內(nèi)存泄漏及解決辦法,有興趣的同學(xué)可以了解一下。2016-11-11
詳解Android開發(fā)錄音和播放音頻的步驟(動(dòng)態(tài)獲取權(quán)限)
這篇文章主要介紹了詳解Android開發(fā)錄音和播放音頻的步驟(動(dòng)態(tài)獲取權(quán)限),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

