Article title: encapsulation of Retrofit2+Rxjava2 network request framework

Based on the networking framework of Retrofit and Rxjava2, the builder mode constructs RestClient, encapsulates the request method, supports configuration loading animation, and chain call. Unified request to get the original data returned by the background.

Let's take a look at the network request sample code

Chain call, concise and clear

     * Request network
     *
     * @param view
     */
    public void request(View view) {
        RestClient restClient = RestClient.builder()
                .url("data/Android/10/1")
                .load(this)
//                .params(new WeakHashMap<String, Object>())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {

                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build();
        restClient.request(HttpMethod.GET);
    }
//Write code here

Add dependency: unified management of dependency is used here

--------------------
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile rootProject.ext.dependencies.appcompatV7
    implementation rootProject.ext.dependencies.constraintLayout
    compile rootProject.ext.dependencies.design
    compile rootProject.ext.dependencies.cardView
    compile rootProject.ext.dependencies.systembartint
    //Retrofit and Rxjava
    compile rootProject.ext.dependencies.rxjava2
    compile rootProject.ext.dependencies.rxandroid2
    compile rootProject.ext.dependencies.retrofit2
    compile rootProject.ext.dependencies.converterGson
    compile rootProject.ext.dependencies.converterScalars
    compile rootProject.ext.dependencies.adapterRxjava2
    //Load animation
    compile rootProject.ext.dependencies.aviloader
    //okhttp3 interceptor
    compile rootProject.ext.dependencies.loggerinterceptor
    testImplementation rootProject.ext.dependencies.junit
    androidTestImplementation rootProject.ext.dependencies.runner
    androidTestImplementation rootProject.ext.dependencies.espresso
}

HttpMethod enumeration class defines request method

 * Created by kevin321vip on 2017/12/14.
 * Request method,Enumeration class
 */

public enum HttpMethod {
    GET,
    POST,
    POST_RAW,
    PUT,
    PUT_RAW,
    DELETE,
    UPLOAD

//Write code here

RestService defines a unified API service interface

 * Created by kevin321vip on 2017/12/14.
 * Api Interface
 */

public interface RestService {
    @GET
    Observable<String> get(@Url String url, @QueryMap WeakHashMap<String, Object> params);

    @FormUrlEncoded
    @POST
    Observable<String> post(@Url String url, @QueryMap WeakHashMap<String, Object> params);

    @POST
    Observable<String> post(@Url String url, ResponseBody body);

    @FormUrlEncoded
    @PUT
    Observable<String> put(@Url String url, @FieldMap WeakHashMap<String, Object> params);

    @PUT
    Observable<String> putRaw(@Url String url, @Body RequestBody body);

    @DELETE
    Observable<String> delete(@Url String url, @QueryMap WeakHashMap<String, Object> params);

    @Streaming
    @GET
    Observable<ResponseBody> download(@Url String url, @QueryMap WeakHashMap<String, Object> params);
    @Multipart
    @POST
    Observable<String> upload(@Url String url, @Part MultipartBody.Part file);

}
//Write code here

Restcreator (key class)

**Initialization configuration of the main Retroft and return of the ApiService object
1. It is mainly about the singleton object acquisition of static internal Hodler like mode**
2,.addConverterFactory(Sca larsConverterFactory.create () ensure that the returned data is the original request data, which is convenient to filter and verify the relevant processing according to the status
3. ParamsHodler single instance management Params multiple uses without repeating new objects**

    /**
     * Building a global Retrofit client
     * .baseUrl(UrlConstance.BaseUrl)
     * .addConverterFactory(GsonConverterFactory.create())
     * http://gank.io/api/data/Android/10/1
     */
    private static final class RetrofitHodler {
        private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
                .client(OkHttpHodler.OK_HTTP_CLIENT)
                .baseUrl("http://gank.io/api/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * OkhttpHodler
     */
    private static final class OkHttpHodler {
        private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
                .connectTimeout(UrlConstance.TimeOut, TimeUnit.SECONDS)
                .build();
    }

    /**
     * RestService
     */
    private static final class RestServiceHodler {
        private static final RestService REST_SERVICE = RetrofitHodler.RETROFIT_CLIENT.create(RestService.class);
    }

    /**
     * Params Hodler of
     */
    private static final class ParamsHodler {
        private static final WeakHashMap<String, Object> PARAMS = new WeakHashMap<>();
    }

    /**
     * Get parameters
     *
     * @return
     */
    public static WeakHashMap<String, Object> getParams() {
        return ParamsHodler.PARAMS;
    }

    /**
     * Get Service
     */
    public static RestService getService() {
        return RestServiceHodler.REST_SERVICE;
    }
}

//Write code here

*

RestClient key class*

It is used to initiate network requests, pass in request parameters and Build request body through Build mode

     * Pass on parameters through builder mode
     */
    public static RestClientBuilder builder() {
        return new RestClientBuilder();
    }

    /**
     * Initiate network request
     */
    public void request(HttpMethod method) {
    //Obtain the API service object, and send a request to the observable instantiation through the corresponding request method
        final RestService service = RestCreator.getService();
        Observable<String> observable = null;
        if (REQUEST != null) {
            REQUEST.onRequestStart();
        }
        if (LOADER_STYLE != null) {
            LyonLoader.showLoading(CONTEXT, LOADER_STYLE);
        }
        switch (method) {
            case GET:
                observable = service.get(URL, PARAMS);
                break;
            case POST:
                service.post(URL, PARAMS);
                observable = service.post(URL, PARAMS);
                break;
            case POST_RAW:
//                observable = service.postRaw(URL, BODY);
                break;
            case PUT:
                observable = service.post(URL, PARAMS);
                break;
            case PUT_RAW:
                service.putRaw(URL, BODY);
                break;
            case DELETE:
                observable = service.delete(URL, PARAMS);
                break;
            case UPLOAD:
                final RequestBody requestBody =
        RequestBody.create(MediaType.parse(MultipartBody.FORM.toString()), FILE);
                final MultipartBody.Part body =
                        MultipartBody.Part.createFormData("file", FILE.getName(), requestBody);
                observable = service.upload(URL, body);
                break;
            default:
                break;
        }
        //Initiate a network request and call back the requested data in the callback
        if (observable != null) {
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }
                        @Override
                        public void onNext(String s) {
                            if (SUCCESS != null) {
                                SUCCESS.onSuccess(s);
                            }
                            LyonLoader.stopLoading();
                            ToastUtils.show("Request succeeded" + s);
                        }

                        @Override
                        public void onError(Throwable e) {
                            LyonLoader.stopLoading();
                            if (ERROR != null) {
                                ERROR.onError(0, e.getMessage());
                            }
                            ToastUtils.show("request was aborted" + e.getMessage());

                        }

                        @Override
                        public void onComplete() {

                        }
                    });


        }
    }

    /**
     * get method
     */
    public void get() {
        request(HttpMethod.GET);
    }

    /**
     * post method
     */
    public void post() {
        request(HttpMethod.POST);
    }
}
**stay Retrofit According to the incoming callback interface, the result of the request will be sent out**

RestClientBuilder builder

Constructor of RestClient, which is used to pass in configuration information of networking request and construct Reclient object

* Created by kevin321vip on 2017/12/14.
* RestClient Builder of
*/

public class RestClientBuilder {
private final WeakHashMap<String, Object> PARAMS = RestCreator.getParams();
private String URL = null;
private IRequest REQUEST = null;
private String DOWNLOAD_DIR = null;
private String EXTENSION = null;
private String NAME = null;
private ISuccess SUCCESS = null;
private IFailure FAILURE = null;
private IError ERROR = null;
private RequestBody BODY = null;
private LoadStyle LOADER_STYLE = null;
private File FILE = null;
private Context CONTEXT = null;

public final RestClientBuilder params(WeakHashMap<String, Object> params) {
PARAMS.putAll(params);
return this;
}

public final RestClientBuilder params(String key, Object value) {
PARAMS.put(key, value);
return this;
}

public final RestClientBuilder url(String url) {
this.URL = url;
return this;
}

public final RestClientBuilder request(IRequest iRequest) {
this.REQUEST = iRequest;
return this;
}

public final RestClientBuilder failure(IFailure iFailure) {
this.FAILURE = iFailure;
return this;
}

public final RestClientBuilder success(ISuccess iSuccess) {
this.SUCCESS = iSuccess;
return this;
}

public final RestClientBuilder error(IError iError) {
this.ERROR = iError;
return this;
}

public final RestClientBuilder dir(String downloaddir) {
this.DOWNLOAD_DIR = downloaddir;
return this;
}

public final RestClientBuilder extension(String extension) {
this.EXTENSION = extension;
return this;
}

public final RestClientBuilder name(String name) {
this.NAME = name;
return this;
}

public final RestClientBuilder body(RequestBody body) {
this.BODY = body;
return this;
}

public final RestClientBuilder LoadStyle(LoadStyle loadStyle) {
this.LOADER_STYLE = loadStyle;
return this;
}

public final RestClientBuilder file(File file) {
this.FILE = file;
return this;
}

public final RestClientBuilder load(Context context, LoadStyle loadStyle) {
this.CONTEXT = context;
this.LOADER_STYLE = loadStyle;
return this;
}

public final RestClientBuilder load(Context context) {
this.CONTEXT = context;
this.LOADER_STYLE = LoadStyle.BallClipRotatePulseIndicator;
return this;
}

public final RestClient build() {
return new RestClient(URL, REQUEST, DOWNLOAD_DIR
, EXTENSION, NAME, SUCCESS, FAILURE, ERROR, BODY, LOADER_STYLE
, FILE, CONTEXT);
}
}

//Write code here

I don't want to introduce the Loader, but I use the big God's:* com.wang.avi:library:2.1.3 Made some packaging*
To view the complete code, please move to my github:
code implementation
.

Tags: Retrofit network Android Junit

Posted on Fri, 22 May 2020 12:23:59 -0400 by EPCtech