Retrofit network loading library secondary encapsulation supports RxJava and Flow-HttpUtils

Retrofit network loading library secondary encapsulation supports RxJava and Flow-HttpUtils

HttpUtils is a secondary encapsulation of the Retrofit network loading library that supports RxJava and Flow, 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:HttpUtils:2.3.0'
//库所使用的三方
implementation 'androidx.lifecycle:lifecycle-common:2.4.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.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.okhttp3:logging-interceptor:5.0.0-alpha.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
implementation 'androidx.work:work-runtime-ktx:2.7.1'

//如果不需要rxjava不用导入
implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'

implementation 'com.github.DL-ZhangTeng:Utils:2.1.1'

Attributes

attribute name describe
setBaseUrl ConfigGlobalHttpUtils() global BaseUrl; ConfigSingleInstance() sets BaseUrl individually
addCallAdapterFactory 设置CallAdapter.Factory,默认FlowCallAdapterFactory.create()、CoroutineCallAdapterFactory.create()、RxJava2CallAdapterFactory.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
setHttpCallBack Set the callback function before and after the network request onHttpResponse: You can get the result of each Http request one step before the client onHttpRequest: You can get it before requesting the server
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
addInterceptor Add an interceptor (inherit PriorityInterceptor and override the getPriority method to customize the order. Custom interceptor Priority must be >= 10)
addInterceptors Add an interceptor (inherit PriorityInterceptor and override the getPriority method to customize the order. Custom interceptor Priority must be >= 10)
addNetworkInterceptor Add a network interceptor (inherit PriorityInterceptor and override the getPriority method to customize the order. Custom interceptor Priority must be >= 10)
addNetworkInterceptors Add a network interceptor (inherit PriorityInterceptor and override the getPriority method to customize the order. Custom interceptor Priority must be >= 10)
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

initialization

class HttpUtilsApplication : Application() {
    
    

    override fun onCreate() {
    
    
        super.onCreate()
        HttpUtils.init(this)
        HttpUtils.instance
            .ConfigGlobalHttpUtils()
            //全局的BaseUrl
            .setBaseUrl("https://www.wanandroid.com/")
            //设置CallAdapter.Factory,默认FlowCallAdapterFactory.create()、CoroutineCallAdapterFactory.create()、RxJava2CallAdapterFactory.create()
            .addCallAdapterFactory(CoroutineCallAdapterFactory.create())
            .addCallAdapterFactory(FlowCallAdapterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            //设置Converter.Factory,默认GsonConverterFactory.create()
            .addConverterFactory(GsonConverterFactory.create(FailOverGson.failOverGson))
            //设置自定义域名解析
            //.setDns(HttpDns.getInstance())
            //开启缓存策略
            .setCache(true)
            //全局的单个请求头信息
            //.addHeader("Authorization", "Bearer ")
            //全局的静态请求头信息
            //.setHeaders(headersMap)
            //全局的请求头信息,需要Android
            //.setHeaders(headersMap) { headers ->
            //    headers.apply {
    
    
            //        this["version"] = BuildConfig.VERSION_CODE
            //        this["os"] = "android"
            //        val isLogin = BuildConfig.DEBUG
            //        if (isLogin) {
    
    
            //            this["Authorization"] = "Bearer " + "token"
            //        } else {
    
    
            //            this.remove("Authorization")
            //        }
            //    }
            //}
            //全局的动态请求头信息
            .setHeaders {
    
     headers ->
                headers.apply {
    
    
                    this["version"] = BuildConfig.VERSION_CODE
                    this["os"] = "android"
                    val isLogin = BuildConfig.DEBUG
                    if (isLogin) {
    
    
                        this["Authorization"] = "Bearer " + "token"
                    } else {
    
    
                        this.remove("Authorization")
                    }
                }
            }
            //.setHttpCallBack(object : CallBack {
    
    
            //    override fun onHttpResponse(
            //        chain: Interceptor.Chain,
            //        response: Response
            //    ): Response {
    
    
            //        //这里可以先客户端一步拿到每一次 Http 请求的结果
            //        val body: ResponseBody? = response.newBuilder().build().body
            //        val source = body?.source()
            //        try {
    
    
            //            source?.request(Long.MAX_VALUE) // Buffer the entire body.
            //        } catch (e: IOException) {
    
    
            //            e.printStackTrace()
            //        }
            //        val buffer: Buffer? = source?.buffer
            //        var charset: Charset = StandardCharsets.UTF_8
            //        val contentType: MediaType? = body?.contentType()
            //        if (contentType != null) {
    
    
            //            charset = contentType.charset(charset)!!
            //        }
            //        buffer?.readString(charset).e()
            //        return response
            //    }
            //
            //    override fun onHttpRequest(chain: Interceptor.Chain, request: Request): Request {
    
    
            //        //这里可以在请求服务器之前拿到
            //        FailOverGson.failOverGson.toJson(request.headers).e()
            //        val body: RequestBody? = request.body
            //        try {
    
    
            //            body?.contentLength().toString().e()
            //        } catch (e: IOException) {
    
    
            //            e.printStackTrace()
            //        }
            //        return request
            //    }
            //})
            //全局持久话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)
    }
}

ICallBack callback (please refer to MainActivity for more request methods)

    fun deferredGo_ICallBack() {
    
    
    GlobalScope.launch {
    
    
        HttpUtils.instance.ConfigGlobalHttpUtils()
            .createService(Api::class.java)
            .getHomeListByDeferred(0)
            .deferredGo(object :
                DeferredCallBack<BaseResult<HomeListBean>>(
                    this@MainActivity
                ) {
    
    
                override fun isHideToast(): Boolean {
    
    
                    return true
                }

                override fun onFailure(iException: IException?) {
    
    
                    FailOverGson.failOverGson.toJson(iException).e("deferredGo_ICallBack")
                }

                override fun onSuccess(t: BaseResult<HomeListBean>) {
    
    
                    FailOverGson.failOverGson.toJson(t).e("deferredGo_ICallBack")
                }
            })
    }
}

fun deferredGoIResponse_ICallBack() {
    
    
    GlobalScope.launch {
    
    
        HttpUtils.instance.ConfigGlobalHttpUtils()
            .createService(Api::class.java)
            .getHomeListByDeferred(0)
            .deferredGoIResponse(object :
                DeferredCallBack<IResponse<HomeListBean>>(
                    this@MainActivity
                ) {
    
    
                override fun isHideToast(): Boolean {
    
    
                    return true
                }

                override fun onFailure(iException: IException?) {
    
    
                    FailOverGson.failOverGson.toJson(iException).e("deferredGoIResponse_ICallBack")
                }

                override fun onSuccess(t: IResponse<HomeListBean>) {
    
    
                    FailOverGson.failOverGson.toJson(t).e("deferredGoIResponse_ICallBack")
                }
            })
    }
}

fun flowGo_ICallBack() {
    
    
    GlobalScope.launch(Dispatchers.Main) {
    
    
        HttpUtils.instance.ConfigGlobalHttpUtils()
            .createService(Api::class.java)
            .getHomeListByFlow(0)
            .flowGo(object :
                FlowCallBack<BaseResult<HomeListBean>>(this@MainActivity) {
    
    
                override fun isHideToast(): Boolean {
    
    
                    return true
                }

                override fun onFailure(iException: IException?) {
    
    
                    FailOverGson.failOverGson.toJson(iException).e("flowGo_ICallBack")
                }

                override fun onSuccess(t: BaseResult<HomeListBean>) {
    
    
                    FailOverGson.failOverGson.toJson(t).e("flowGo_ICallBack")
                }
            })
    }
}

fun flowGoIResponse_ICallBack() {
    
    
    GlobalScope.launch(Dispatchers.Main) {
    
    
        HttpUtils.instance.ConfigGlobalHttpUtils()
            .createService(Api::class.java)
            .getHomeListByFlow(0)
            .flowGoIResponse(object :
                FlowCallBack<IResponse<HomeListBean>>(this@MainActivity) {
    
    
                override fun isHideToast(): Boolean {
    
    
                    return true
                }

                override fun onFailure(iException: IException?) {
    
    
                    FailOverGson.failOverGson.toJson(iException).e("flowGoIResponse_ICallBack")
                }

                override fun onSuccess(t: IResponse<HomeListBean>) {
    
    
                    FailOverGson.failOverGson.toJson(t).e("flowGoIResponse_ICallBack")
                }
            })
    }
}

fun observableGoCompose() {
    
    
    HttpUtils.instance
        .ConfigGlobalHttpUtils()
        .createService(Api::class.java)
        .getHomeListByObservable(0)
        //页面销毁自动取消请求
        .compose(LifecycleObservableTransformer(this@MainActivity))
        //自动处理网络加载中动画
        .compose(ProgressDialogObservableTransformer(this@MainActivity))
        .subscribe(object : CommonObserver<IResponse<HomeListBean>>() {
    
    
            override fun onFailure(iException: IException?) {
    
    
                FailOverGson.failOverGson.toJson(iException).e("rxjavaGo")
            }

            override fun onSuccess(t: IResponse<HomeListBean>) {
    
    
                FailOverGson.failOverGson.toJson(t).e("rxjavaGo")
            }
        })
}

fun observableGoObserver() {
    
    
    HttpUtils.instance
        .ConfigGlobalHttpUtils()
        .createService(Api::class.java)
        .getHomeListByObservable(0)
        //页面销毁自动取消请求
        //自动处理网络加载中动画
        .subscribe(object : CommonObserver<IResponse<HomeListBean>>(this@MainActivity) {
    
    
            override fun onFailure(iException: IException?) {
    
    
                FailOverGson.failOverGson.toJson(iException).e("rxjavaGo")
            }

            override fun onSuccess(t: IResponse<HomeListBean>) {
    
    
                FailOverGson.failOverGson.toJson(t).e("rxjavaGo")
            }
        })
}

//手动取消网络请求
//        HttpUtils.instance.cancelSingleRequest(any);
//        HttpUtils.instance.cancelAllRequest();

Confuse

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

historic version

Version renew Update time
v2.3.0 Flow function data parsing problem fixed 2023/2/3 at 21:05
v2.2.0 Add file upload breakpoint download 2022/11/9 at 16:41
v2.1.0 Common data parsing fault tolerance processing 2022/10/31 at 17:47
v2.0.0 Retrofit network loading library secondary encapsulation supports RxJava and Flow-HttpUtils 2022/9/15 at 0:17

Appreciate

If you like HttpUtils, or feel that HttpUtils 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/126879568