RxJava+Retrofit network loading library secondary encapsulation-RxHttpUtils

RxJava+Retrofit network loading library secondary encapsulation-RxHttpUtils

RxHttpUtils is a secondary encapsulation of RxJava+Retrofit network loading library, including network loading animation, activity destruction automatic cancellation request, network cache, public parameters, RSA+AES encryption, etc. GitHub warehouse
address

introduce

gradle

allprojects {
    
    
    repositories {
    
    
        maven {
    
     url 'https://jitpack.io' }
    }
}

implementation 'com.github.DL-ZhangTeng:RxHttpUtils:1.4.0'
    //库所使用的三方
    implementation 'androidx.lifecycle:lifecycle-common:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-runtime:2.4.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.8.1'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
    //noinspection GradleDynamicVersion
    implementation 'com.github.DL-ZhangTeng.BaseLibrary:utils:1.4.+'

Attributes

attribute name describe
setBaseUrl ConfigGlobalHttpUtils() global BaseUrl; ConfigSingleInstance() sets BaseUrl individually
addCallAdapterFactory Set CallAdapter.Factory, default RxJavaCallAdapterFactory.create()
addConverterFactory Set Converter.Factory, default GsonConverterFactory.create()
setDns Custom domain name resolution
setCache Enable cache policy
addHeader Global single request header information
setHeaders Global request header information, set static request headers: no need to reset when updating request headers, just remove and add Map elements; set dynamic request headers: such as token and other request header parameters that need to change in real time according to the login status, minimum Support API 24
setSign For global signature verification, appKey only needs to match the backend. For specific rules, please refer to: https://blog.csdn.net/duoluo9/article/details/105214983
setEnAndDecryption Global encryption and decryption (AES+RSA). 1. Public key request path HttpUrl.get(BuildConfig.HOST + “/getPublicKey”); 2. Public key response result {“result”: {“publicKey”: “”}, “message”: “Query successful!”, "status": 100}
setCookie Global persistent cookies, saved locally, will be carried in the header every time
setSslSocketFactory Global ssl certificate authentication. 1. Trust all certificates, which are insecure and risky, setSslSocketFactory(); 2. Use pre-embedded certificates to verify the server certificate (self-signed certificate), setSslSocketFactory(getAssets().open("your.cer")); 3. , use bks certificate and password to manage client certificate (two-way authentication), use embedded certificate, verify server certificate (self-signed certificate), setSslSocketFactory(getAssets().open("your.bks"), "123456", getAssets().open(“your.cer”))
setReadTimeOut Global timeout configuration
setWriteTimeOut Global timeout configuration
setConnectionTimeOut Global timeout configuration
setLog Whether to enable request log globally

use

 public class MainApplication extends Application {
    
    
     private static MainApplication mainApplication;
     private final Map<String, Object> headersMap = new HashMap<>();

     public static MainApplication getInstance() {
    
    
         return mainApplication;
     }

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        HttpUtils.init(this);
        HttpUtils.getInstance()
                .ConfigGlobalHttpUtils()
                //全局的BaseUrl
                .setBaseUrl("http://**/")
                //设置CallAdapter.Factory,默认RxJavaCallAdapterFactory.create()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //设置Converter.Factory,默认GsonConverterFactory.create()
                .addConverterFactory(GsonConverterFactory.create())
                //设置自定义域名解析
                .setDns(HttpDns.getInstance())
                //开启缓存策略
                .setCache(true)
                //全局的单个请求头信息
                .addHeader("Authorization", "Bearer ")
                //全局的静态请求头信息
                //.setHeaders(headersMap)
                //全局的请求头信息
                //.setHeaders(headersMap, headers -> {
    
    
                //  if (headers == null) {
    
    
                //      headers = new HashMap<>();
                //  }
                //  boolean isLogin = BuildConfig.DEBUG;
                //  if (isLogin) {
    
    
                //      headers.put("Authorization", "Bearer " + "token");
                //  } else {
    
    
                //      headers.remove("Authorization");
                //  }
                //  return headers;
                //})
                //全局的动态请求头信息
                .setHeaders(headers -> {
    
    
                    if (headers == null) {
    
    
                        headers = new HashMap<>();
                    }
                    headers.put("version", BuildConfig.VERSION_CODE);
                    headers.put("os", "android");

                    boolean isLogin = BuildConfig.DEBUG;
                    if (isLogin) {
    
    
                        headers.put("Authorization", "Bearer " + "token");
                    } else {
    
    
                        headers.remove("Authorization");
                    }
                    return headers;
                })
                //全局持久话cookie,保存本地每次都会携带在header中
                .setCookie(false)
                //全局ssl证书认证
                //信任所有证书,不安全有风险
                .setSslSocketFactory()
                //使用预埋证书,校验服务端证书(自签名证书)
                //.setSslSocketFactory(getAssets().open("your.cer"))
                //使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书)
                //.setSslSocketFactory(getAssets().open("your.bks"), "123456", getAssets().open("your.cer"))
                //全局超时配置
                .setReadTimeOut(10)
                //全局超时配置
                .setWriteTimeOut(10)
                //全局超时配置
                .setConnectionTimeOut(10)
                //全局是否打开请求log日志
                .setLog(true);
    }
}
//使用生命周期监听自动取消请求、加载中动画自动处理(LifecycleObservableTransformer、ProgressDialogObservableTransformer)
 HttpUtils.getInstance()
                .ConfigGlobalHttpUtils()
                .createService(ApiService.class)
                .loginPwd("admin", "admin")
                .compose(new LifecycleObservableTransformer<>(MainActivity.this))
                .compose(new ProgressDialogObservableTransformer<>(mProgressDialog))
                .subscribe(new BaseObserver<BaseResponse<LoginBean>>() {
    
    
                    @Override
                    public void doOnSubscribe(Disposable d) {
    
    

                    }

                    @Override
                    public void doOnError(IException iException) {
    
    

                    }

                    @Override
                    public void doOnNext(BaseResponse<LoginBean> loginBeanBaseResponse) {
    
    

                    }

                    @Override
                    public void doOnCompleted() {
    
    

                    }
                });
                
//使用生命周期监听自动取消请求、加载中动画自动处理(CommonObserver方案)
//        HttpUtils.getInstance()
//                .ConfigSingleInstance()
//                .setBaseUrl("https://**/")
//                .createService(ApiService.class)
//                .loginPwd("admin", "admin")
//                .subscribeOn(Schedulers.io())
//                .doOnSubscribe(disposable -> mProgressDialog.show())
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new CommonObserver<BaseResponse<LoginBean>>(mProgressDialog) {
    
    
//                    @Override
//                    protected void onFailure(IException iException) {
    
    
//
//                    }
//
//                    @Override
//                    protected void onSuccess(BaseResponse<LoginBean> loginBeanBaseResponse) {
    
    
//                        ToastUtilsKt.showShortToast(MainActivity.this, loginBeanBaseResponse.getMsg());
//                    }
//                });

//手动取消网络请求
//        HttpUtils.getInstance().cancelSingleRequest(this);
//        HttpUtils.getInstance().cancelSingleRequest(Disposable);
//        HttpUtils.getInstance().cancelAllRequest();

Confuse

-keep public class com.zhangteng.**.*{ *; }

historic version

Version renew Update time
v1.4.0 Throw IException when using rxJava to facilitate debugging 2022/8/22 at 10:46
v1.3.0 增加addConverterFactory&addCallAdapterFactory&addHeader 2022/7/9 at 13:07
v1.2.2 Use IException in the util library to solve cyclic dependencies & exception handling is implemented in subclasses to facilitate debugging exceptions 2022/7/4 at 17:50
v1.2.1 Add dynamic request header adding method & customize domain name resolution 2022/6/25 at 16:46
v1.2.0 Use base library utils 2022/1/21 at 20:14
v1.1.9 ConcurrentModificationException error report 2022/1/2 at 21:28
v1.1.8 Download file configuration 2021/12/21 at 23:42
v1.1.7 File upload supports custom field names 2021/10/28 at 17:06
v1.1.6 Modification of the request cancellation plan: 1. Add the ObservableTransformer plan to automatically cancel requests for Lifecycle life cycle monitoring; 2. Automatically remove from the collection after the request is completed; 3. Automatically remove all requests corresponding to Tags upon page destruction. 2021/10/9 at 15:38
v1.1.5 1. Add Lifecycle life cycle monitoring to automatically cancel requests; 2. Add cancellation requests through tags 2021/9/22 at 16:43
v1.1.4 1. Use RetrofitServiceProxyHandler when creating Service; 2. Upload and download singleton bug 2021/7/15 at 15:36
v1.1.3 Single interface configuration and global configuration synchronization method & Support UnitTest 2021/7/12 at 17:45
v1.1.2 Increase the lru cache of Service 2021/5/10 at 16:25
v1.1.1 Encryption and decryption failure build response bug 2020/12/14 at 18:04
v1.1.0 Migrate to androidx 2020/7/22 at 13:40
v1.0.3 Global interceptor failure bug 2020/6/27 at 12:22
v1.0.2 Add permissions and change the module name to lowercase 2020/6/11 at 9:45
v1.0.1 Package structure adjustment 2020/6/11 at 9:36
v1.0.0 First edition 2020/6/3 at 17:13

Appreciate

If you like RxHttpUtils, or feel that RxHttpUtils has helped you, you can click "Star" in the upper right corner to support it. Your support is my motivation, thank you.

contact me

Email: [email protected]/[email protected]

License

Copyright © [2020] [Swing]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Guess you like

Origin blog.csdn.net/duoluo9/article/details/120698648