概述
在android開發(fā)中經(jīng)常要訪問網(wǎng)絡(luò)般码,目前最流行的網(wǎng)絡(luò)訪問框架就是Okhttp了,然而我們?cè)诰唧w使用時(shí)乱顾,往往仍然需要二次封裝板祝。我使用Builder設(shè)計(jì)模式進(jìn)行了封裝形成oknet開源庫。
介紹
oknet是一套基于okhttp的android網(wǎng)絡(luò)http框架,封裝了請(qǐng)求參數(shù)處理走净,日志打印券时。
名稱:oknet
github地址:https://github.com/vir56k/oknet
作者: zhangyunfeiVir
特性
1.簡潔的語法
2.支持自定義處理 message code 不等于0 的情形
3.支持文件上傳
4.完整清晰的log日志輸出
5.支持 公共參數(shù) 的配置
6.支持每個(gè)http請(qǐng)求的 日志 記錄
7.支持 默認(rèn)異常 的處理
8.支持 移除文件下載(通過FileDownloader)
適用場景
和服務(wù)端產(chǎn)生約定消息結(jié)構(gòu):
返回的響應(yīng)的json格式一定為:
{code:0, msg:"", body:""}
參數(shù)說明:
1.服務(wù)端 響應(yīng)成功 則返回對(duì)應(yīng)的json
2.code=0表示成功,body里如正確響應(yīng)json.
3.code非零表示失敗伏伯,msg表示失敗的文本橘洞。
4.body 節(jié)點(diǎn)里放置你的自定義json數(shù)據(jù)
引用
在你的項(xiàng)目的根目錄下的 build.gradle 文件中添加引用
compile 'zhangyf.vir56k:oknet:0.0.1'
示例:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'zhangyf.vir56k:oknet:0.0.1'
}
在系統(tǒng)啟動(dòng)時(shí)進(jìn)行一些配置
比如在你的繼承自Application的子類中,或者主Activity啟動(dòng)時(shí)配置说搅。
//配置okhttp 緩存位置
OknetConfig.setExternalCacheDir(getExternalCacheDir());
//OknetConfig.setRequestParaInterceptor(new CustomRequestParaInterceptor1());
OknetConfig.setRequestParaInterceptor(new CustomRequestParaInterceptor_jlb_app());
OknetConfig.setDefaultExceptionHandler(new CustomDefalutExceptionHandler());
OknetConfig.setLogInterceptor(new LogInterceptor() {
@Override
public void onLog(String tag, String msg) {
//Log.i("日志攔截器攔截到 tag =" + tag, " msg = " + msg);
}
});
post簡單請(qǐng)求炸枣,和String類型的響應(yīng)
RequestBuilder.with(getActivity()).URL(Apis.GAEA_URLS.CAB_ADVERT_LIST).
onSuccess(new CommonCallback<String>(String.class) {
@Override
public void onSuccess(String result, CommonMessage responseMessage, String responseString) {
Log.i(TAG, "==成功:" + result);
alert("==成功");
}
}).excute();
帶參數(shù)的請(qǐng)求,和 Json序列化的回調(diào)
Type t = new TypeToken<List<Demo2Cell>>() {
}.getType();
RequestBuilder.with(getActivity())
.URL(Apis.Cab_Urls.GET_BOX_FREE_NEWS)
.para("cabinet_code", "1412345678")
.onSuccess(new CommonCallback<List<Demo2Cell>>(t) {
@Override
public void onSuccess(List<Demo2Cell> result, CommonMessage responseMessage, String responseString) {
Log.i(TAG, "!!! 成功:" + result.get(0));
alert("!!成功" + result.get(0));
}
})
.excute();
自定義處理異常代碼(服務(wù)返回的消息里的 message code 不等于0) 的情形
RequestBuilder.with(getActivity())
.URL(Apis.GAEA_URLS.CAB_ADVERT_LIST)
.onSuccess(new CommonCallback<String>(String.class) {
@Override
public void onSuccess(String result, CommonMessage responseMessage, String responseString) {
Log.i(TAG, "==成功:" + result);
alert("==成功");
}
@Override
public boolean onFailure(int httpCode, Exception ex, CommonMessage responseMessage, String responseString) {
if (ex instanceof NoZeroException) {
NoZeroException noZeroException = (NoZeroException) ex;
int code = noZeroException.getCode();
Log.i(TAG, "!!!!!!!!失敗:" + noZeroException);
alert("!!!!!!!!!!!!!!!!失敗," + noZeroException);
//return false;//如果不需要 默認(rèn)異常處理器再次處理蜓堕,這里可以返回true
}
return super.onFailure(httpCode, ex, responseMessage, responseString);
}
})
.excute();
上傳文件
File f = new File(Environment.getExternalStorageDirectory().getPath(), "ImageCache/CloseIcon.png");
if (!f.exists())
throw new RuntimeException("not found ImageCache/CloseIcon.png");
RequestBuilder.with(getActivity())
.URL("http://10.0.1.232:8888/uc/suser/upload_avatar")
.para("uid", "100202")
.para("sid", "50e2904ca493d5d25475e4e080858925")
/************************ 威力僅僅在這一行,其他都一樣 ***************************/
.file("file", f)
/************************ 威力僅僅在這一行,其他都一樣 ***************************/
.onSuccess(new CommonCallback<Demo3Bean>(Demo3Bean.class) {
@Override
public void onSuccess(Demo3Bean result, CommonMessage responseMessage, String responseString) {
Log.i(TAG, "!!! 成功:" + result.count);
alert("!!成功" + result.count);
}
})
.excute();
處理需要顯示進(jìn)度條的情形
RequestBuilder.with(getActivity())
.URL(Apis.GAEA_URLS.CAB_NOTICE_LIST)
.para("cabinet_code", "1412345678")
/******** 沒錯(cuò)尺上,你沒有看錯(cuò)晃危,僅僅 下面 一行,進(jìn)度條就閃亮登場 ************/
.progress(new DialogProgressIndicator(getActivity()))
/******** 沒錯(cuò),你沒有看錯(cuò)囤攀,僅僅 上面 一行,進(jìn)度條就閃亮登場 ************/
.onSuccess(new CommonCallback<Demo3Bean>(Demo3Bean.class) {
@Override
public void onSuccess(Demo3Bean result, CommonMessage responseMessage, String responseString) {
Log.i(TAG, "!!! 成功:" + result.count);
alert("!!成功" + result.count);
}
})
.excute();
這里的 DialogProgressIndicator類 是一個(gè)“進(jìn)度條指示器”對(duì)象裁赠。
同步的方式發(fā)送http請(qǐng)求
private void demo_syncExcuete() {
new AsyncTask<Void, Void, Void>() {
boolean isok;
String mResult1;
@Override
protected Void doInBackground(Void... params) {
RequestBuilder.with(getActivity())
.URL(Apis.GAEA_URLS.CAB_ADVERT_LIST)
.para("cabinet_code", "1412345678")
.onSuccess(new CommonCallback<String>(String.class) {
@Override
public void onSuccess(String result, CommonMessage responseMessage, String responseString) {
isok = true;
mResult1 = result;
}
@Override
public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) {
isok = false;
return super.onFailure(httpCode, exception, responseMessage, allResponseString);
}
})
.syncExcute();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (isok) {
Log.i(TAG, "==成功:" + mResult1);
alert("==成功");
}
}
}.execute();
}
下載文件
public static void downloadFileDemo() {
String url = "http://d.hiphotos.baidu.com/zhidao/pic/item/08f790529822720e67a9065978cb0a46f21fab2a.jpg";
File dest = new File(Environment.getExternalStorageDirectory(), "6f21fab2a.jpg");
FileDownloader.downloadFile(url, dest, new FileDownloader.DownloadFileProgressListener2() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Err: " + e.getMessage());
}
@Override
public void onProgress(long bytesRead, long contentLength, boolean done) {
System.out.println(String.format("文件下載進(jìn)度, read %s/%s", bytesRead, contentLength));
}
@Override
protected void onSuccess(Call call, File file) {
System.out.println("文件下載成功嗎 =" + file.exists());
}
});
}