前言:
网络请求是绝大多数app中比不可少的工具,对于我而言,从最初的xutils,到vollay,再到okhttp,最后到了今天的retrofit,相对而言,每个都有每个的优点,并不能完全说谁好谁坏,其实我觉得用你最熟悉的,你觉得最好的,最方便的,他就是最好的,到目前为止,我相信还是有一些公司的项目在用xutils,或者vollay的,如果说盲目的追求新东西,而最后出现一堆bug,这恐怕是所有程序猿最不想看到的结果,只要你技术过硬,你就能封装一套最适合你的,好了废话不多说,下面我就带领大家来简单的封装一套属于你自己的retrofit网络请求,让你的网络请求更简单方便,此封装并没有包含所有请求方式,这里只以get请求为例,其他方式自行开阔,后续会将所有请求方式添加到github源码中,
1.添加相关依赖
//文件内部使用
def butterknifeLatestReleaseVersion = '8.5.1' //butterknife插件的版本
def supportLibraryVersion = '27.1.1'
//外部使用的安卓版本相关
ext {
applicationId = 'com.yc.androidarchitecture'
compileSdkVersion = 27
targetSdkVersion = 27
minSdkVersion = 19
buildToolsVersion = "27.1.1"
versionCode = 0
versionName = "1.0.0"
}
//compile依赖的第三方库
ext.deps = [
supportv4 : "com.android.support:support-v4:$supportLibraryVersion",
supportv7 : "com.android.support:appcompat-v7:$supportLibraryVersion",
recyclerviewv7 : "com.android.support:recyclerview-v7:$supportLibraryVersion",
constraintlayout : 'com.android.support.constraint:constraint-layout:1.1.2',
//增加butterknife 插件相关的库 (版本用内部定义的方式,方便管理)
butterknife : "com.jakewharton:butterknife:$butterknifeLatestReleaseVersion",
butterknifeCompiler : "com.jakewharton:butterknife-compiler:$butterknifeLatestReleaseVersion",
YcAndroidUtils : 'com.yc:YcAndroidUtils:1.1.7',
design : "com.android.support:design:$supportLibraryVersion",
//网络请求依赖库
rxjava : "io.reactivex.rxjava2:rxjava:2.1.1",
rxandroid : "io.reactivex.rxjava2:rxandroid:2.0.1",
retrofit : "com.squareup.retrofit2:retrofit:2.3.0",
retrofit2_converter_gson : "com.squareup.retrofit2:converter-gson:2.3.0",
retrofit2_adapter_rxjava2 : "com.squareup.retrofit2:adapter-rxjava2:2.3.0",
okhttp3_logging_interceptor: "com.squareup.okhttp3:logging-interceptor:3.10.0",
]
2.在base类中创建 BaseApiService,这里只实现get方式,其他的方式根据需求自己添加就好
/**
* Created by yc on 2018/4/3.
*/
public interface BaseApiService {
@GET()
Flowable<ApiResult> get(@Url String url, @QueryMap Map<String, String> map);
@POST()
Flowable<ApiResult> post(@Url String url, @QueryMap Map<String, String> map);
}
3.工具类的封装在代码中详细讲解
/**
* Created by yc on 2018/4/3.
*/
public class RetrofitUtils {
private static final String TAG = "RetrofitUtils";
private static volatile RetrofitUtils instance;
//定义请求服务
private BaseApiService mBaseApiService;
private RetrofitUtils(Object tag) {
//由于Retrofit是基于okhttp的所以,要先初始化okhttp相关配置
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// // BASIC,BODY,HEADERS
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())//利用gson来解析数据,你也可以用其他方式解析
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//结合rxjava 来实现数据回调
.baseUrl(UrlConfig.BASEURL)
.build();
mBaseApiService = retrofit.create(BaseApiService.class);
}
public static RetrofitUtils getInstance() {
return getInstance("");
}
public static RetrofitUtils getInstance(Object tag) {
if (instance == null) {
synchronized (RetrofitUtils.class) {
if (null == instance) {
instance = new RetrofitUtils(tag);
}
}
}
return instance;
}
public BaseApiService getBaseApiService() {
return mBaseApiService;
}
/**
* post
*
* @param url
* @param map
* @param callBackListener
*/
public void get(String url, Map map, final OnRequestCallBackListener callBackListener) {
requestCallBack(url, map, callBackListener);
}
/**
* post
*
* @param url
* @param map
* @param callBackListener
*/
public void post(String url, Map map, final OnRequestCallBackListener callBackListener) {
requestCallBack(url, map, callBackListener);
}
//处理数据请求相关功能,通过接口回调的方式将rxjava返回的数据返回给调用者
private <T> void requestCallBack(String url, Map map, final OnRequestCallBackListener<T> onRequestCallBackListener) {
Flowable flowable = mBaseApiService.get(url, map);
Flowable<ApiResult<T>> newsBeanFlowable1 = flowable.subscribeOn(Schedulers.io());
newsBeanFlowable1.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSubscriber<ApiResult<T>>() {
@Override
public void onNext(ApiResult<T> apiResult) {
onRequestCallBackListener.onSuccess(apiResult);
}
@Override
public void onError(Throwable t) {
onRequestCallBackListener.onFailed(t.getMessage().toString());
}
@Override
public void onComplete() {
}
});
}
}
4.定义回调监听接口
public interface OnRequestCallBackListener<T> {
void onSuccess(ApiResult<T> string);
void onFailed(String e);
}
5.使用方法:
Map map = new HashMap();
RetrofitUtils.getInstance().get(UrlConfig.NEWS_URL, map, new OnRequestCallBackListener() {
@Override
public void onSuccess(ApiResult apiResult) {
}
@Override
public void onFailed(String e) {
}
});
使用方式看起来就是这么简单,这里注意的是url采用的是穿参的方式,并没有用base中注解的方式,可根据需要进行修改
以上就是,安卓框架搭建(六)Retrofit网络请求(简单封装),的全部内容
如有不了解的 可以去github下载源码 本章节内容为分支6
或 加入安卓开发交流群:安卓帮595856941
相关链接:
下一篇: