原文地址:
http://blog.csdn.net/binghongchazuoan/article/details/51968546
相信你们只要用过这个的 都会觉得,没写一个接口都要调用一大堆内容,作为一个处女座兼懒癌晚期的程序员怎么能忍受这个呢,一言不合就得封装这个。 这个逼我装了。看下面代码(半成品,需要写个回调,本人懒得写了)。
public class RetrofitClient {
private static final int DEFAULT_TIMEOUT = 5;
private ApiManager apiManager;
private OkHttpClient okHttpClient;
public static String baseUrl = BuildConfig.HOST_URL;
private static Context mContext;
private static RetrofitClient sNewInstance;
private Retrofit retrofit;
//在访问HttpMethods时创建单例
private static class SingletonHolder {
private static RetrofitClient INSTANCE = new RetrofitClient(
mContext);
}
//获取单例
public static RetrofitClient getInstance(Context context) {
if (context != null) {
DevUtil.v("RetrofitClient", DevUtil.isDebug() + "");
if (!BuildConfig.DEBUG) {
baseUrl = ApiManager.BASE_ONLINE_URL;
}
mContext = context;
}
return SingletonHolder.INSTANCE;
}
//获取单例
public static RetrofitClient getInstance(Context context, String url) {
if (context != null) {
mContext = context;
}
sNewInstance = new RetrofitClient(context, url);
return sNewInstance;
}
//构造方法私有
private RetrofitClient(Context context) {
this(context, null);
}
//构造方法私有
private RetrofitClient(Context context, String url) {
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.cookieJar(new CookieManger(context))
.sslSocketFactory(HttpsHelper.getTrustedFactory(context))
.hostnameVerifier(HttpsHelper.getTrustedVerifier())
.addInterceptor(new BaseInterceptor(mContext))
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(url)
.build();
apiManager = retrofit.create(ApiManager.class);
}
public ApiManager getApiManager() {
return apiManager;
}
}
这里面好多代码都是封装好的,想看的话,以后给你们公布,其实猜大概差不多也能猜到,无非就是请求拦截器header之类,动态注入cookie,加入https请求信任。
好了言归正传,看通用接口吧,等会本文就跑题了,看通用接口吧。
public interface ApiManager {
@POST("{url}")
Observable<Object> getCommonPost(@Path("url") String url,@QueryMap Map<String, String> options);
}
这里只提供了一个post普通参数的,get请求和 file,只要换下请求格式即可,@fileMap ,@Get等等。本文是不完全封装,只提供一条思路,因为项目中暂时不让用,懒得搞了。
public class CommonAPI {
private ApiManager apiManager;
private Context mContext;
public CommonAPI() {
}
public CommonAPI(Context mContext) {
this.mContext = mContext;
}
public void setApiManager(ApiManager apiManager) {
this.apiManager = apiManager;
}
public void commonPost(Subscriber<Object> subscriber, String url, Map<String, String> map) {
RetrofitClient.getInstance(mContext)
.getApiManager()
.getCommonPost(url, map)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
好了 上面已经封装好了,下面看调用的地方
String url = "xxxxx";
HashMap hashMap = new HashMap();
hashMap.put("sSerialNumber", serialNo);
new CommonAPI(context).commonPost(new Subscriber<Object>() {
@Override
public void onCompleted() {
if (showPopup)
acontext.closeLoadingProgress("getDeviceNo");
}
@Override
public void onError(Throwable e) {
DevUtil.v("response", "------------------>" + e.getMessage().toString());
if (showPopup) {
acontext.closeLoadingProgress("getDeviceNo");
}
}
@Override
public void onNext(Object obj) {
DeviceMode mode = null;
if (obj instanceof LinkedTreeMap) {
String jsonStr;
jsonStr = new Gson().toJson(obj);
mode = new Gson().fromJson(jsonStr, DeviceMode .class);
}
iDeviceID = mode.getiDeviceID() + "";
}
}
}, url, hashMap);
关键看这句:
DeviceMode mode = null;
if (obj instanceof LinkedTreeMap) {
String jsonStr;
jsonStr = new Gson().toJson(obj);
mode = new Gson().fromJson(jsonStr, DeviceMode .class);
}
这里已经转化过来了,但是这是半成品,需要再弄个callback,onNext的时候把mode返回给callback的 onNext即可,onComplete、onError 同理。
以后所有普通post请求调new CommonAPI(context).commonPost()即可,不用再自己写一大堆apiManager啥的
封装好了 就特好用了,嘿嘿。本文就此完结,see you next article,bye bye !