1鸯屿、添加依賴
//retrofit網(wǎng)絡(luò)請(qǐng)求框架
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
//retrofit添加Json解析返回?cái)?shù)據(jù)
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
//retrofit添加Rxjava支持
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//rxjava框架
implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
2捞稿、創(chuàng)建 RetrofitFactory (單例模式)
- 創(chuàng)建 OkHttpClient
mOkHttpClient = new OkHttpClient().newBuilder()
.readTimeout(mTimeOut, TimeUnit.SECONDS)
.callTimeout(mTimeOut,TimeUnit.SECONDS)
.writeTimeout(mTimeOut,TimeUnit.SECONDS)
.addInterceptor(new URLInterceptor())//添加過(guò)濾器
.retryOnConnectionFailure(true)//設(shè)置出現(xiàn)錯(cuò)誤進(jìn)行重新連接
.build();
addInterceptor
添加過(guò)濾器点把,可根據(jù)需要進(jìn)行過(guò)濾數(shù)據(jù)
public static class URLInterceptor implements Interceptor {
private String TAG = "okhttp";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")//添加請(qǐng)求頭
// .addHeader("Accept-Encoding", "gzip, deflate")
// .addHeader("Connection", "keep-alive")
// .addHeader("Accept", "*/*")
// .addHeader("Cookie", "add cookies here")
.build()
;
Log.e(TAG,"request:" + request.toString());
long t1 = System.nanoTime();
okhttp3.Response response = chain.proceed(chain.request());
long t2 = System.nanoTime();
Log.e(TAG,String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.e(TAG, "response body:" + content);
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType, content))
// .header("Authorization", Your.sToken)
.build();
//return chain.proceed(request);
}
- 創(chuàng)建Retrofit
public <T> T getService(Class<T> serviceClass) {
if(mRetrofit == null ){
mRetrofit = new Retrofit.Builder()
.baseUrl(BASEURLS_DOMAIN)//添加域名
.client(mOkHttpClient) // 添加mOkHttpClient
.addConverterFactory(GsonConverterFactory.create())//
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return mRetrofit.create(serviceClass);
}
https://ke.4399tech.com/
本次實(shí)戰(zhàn)項(xiàng)目的域名
3警没、封裝BaseResponse與BaseObserver的封裝
BaseResponse
是個(gè)人自定義命名的一個(gè)類葫哗,主要用來(lái)對(duì)返回?cái)?shù)據(jù)進(jìn)行抽象缔刹。
BaseObserver
是對(duì)返回?cái)?shù)據(jù)的基礎(chǔ)數(shù)據(jù)部分進(jìn)行統(tǒng)一處理。
/**
* 創(chuàng)建Base抽象類實(shí)現(xiàn)Observer
*/
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
private static final String TAG = "BaseObserver";
@Override
public void onSubscribe(Disposable d) {
Log.e(TAG, "onSubscribe: " );
}
@Override
public void onNext(BaseResponse<T> response) {
//在這邊對(duì) 基礎(chǔ)數(shù)據(jù) 進(jìn)行統(tǒng)一處理 舉個(gè)例子:
if(response.getRes_code()==200){
onSuccess(response.getResult());
}else{
onSuccess(null,response.getErr_msg(),response.getCode());
}
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "Throwable: " + e.getMessage());
public abstract void onFailure(Throwable e, e.getMessage());
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete: " );
}
public abstract void onSuccess(T demo);
public abstract void onSuccess(T demo, String errorMsg, int code);
public abstract void onFailure(Throwable e,String errorMsg);
4劣针、根據(jù)需求創(chuàng)建請(qǐng)求接口
@GET("/api/apiIndex/getGoodsList")
Observable<BaseResponse<List<GoodsInfo>>> getGoodsList();
//https://blog.csdn.net/jing_80/article/details/82931626
@Multipart
@POST("/api/apiuser/login")
Observable<BaseResponse<String>> loginIn(@PartMap Map<String, RequestBody> requestBodyMap);
請(qǐng)求類型 @GET
@POST
5校镐、請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
RetrofitFactory.getInstance().getService(ApiUrl.class)
.getRetrofit2()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseObserver<Demo>(){
@Override
public void onSuccess(Demo demo) {
Log.e(TAG, "onSuccess: "+demo);
}
@Override
public void onFailure(Throwable e, String errorMsg) {
Log.e(TAG, "onFailure: "+errorMsg);
}
});