# HttpManager **Repository Path**: cbfg5210/HttpManager ## Basic Information - **Project Name**: HttpManager - **Description**: OkHttp 封装 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-09-24 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # HttpManager [![](https://jitpack.io/v/com.gitee.cbfg5210/HttpManager.svg)](https://jitpack.io/#com.gitee.cbfg5210/HttpManager) [本库](https://gitee.com/cbfg5210/HttpManager)是在同事 [superzhangjh](https://github.com/superzhangjh) 的一个代码库基础上进行的修改, 其中基于 [okhttp](https://github.com/square/okhttp)-3.11.0 进行封装,使用并且参考了 [Retrofit](https://github.com/square/retrofit) 的源码。在此对 [superzhangjh](https://github.com/superzhangjh) 和 [okhttp](https://github.com/square/okhttp)、[Retrofit](https://github.com/square/retrofit) 的作者 [Square 公司](https://github.com/square) 表示衷心感谢! [本库](https://gitee.com/cbfg5210/HttpManager)在使用上类似 [Retrofit](https://github.com/square/retrofit),可以视为 [Retrofit](https://github.com/square/retrofit) 的一个简化版。 [本库](https://gitee.com/cbfg5210/HttpManager)支持类似 [Retrofit](https://github.com/square/retrofit) 中的以下注解: @POST、@Body、@Field、@FormUrlEncoded、@GET、@Header、@Headers、@Multipart、@Part、@Path、@POST,其中新添加了两个注解: @HostTag :用于标注 service 接口 @HttpTag : 用于 service 接口添加自己的 tag 信息 [本库](https://gitee.com/cbfg5210/HttpManager)只支持 Get 和 Post 请求方式,Post 请求支持三种类型:json 数据提交(默认 Post 类型,参数注解用 @Field | @Body)、表单数据提交(方法注解用 @FormUrlEncoded,参数注解用 @Field | @Body)、 文件上传(方法注解用 @Multipart,参数注解用 @Part)。 [本库](https://gitee.com/cbfg5210/HttpManager)中的 @Body 注解和 [Retrofit](https://github.com/square/retrofit) 中的用法并不相同, [本库](https://gitee.com/cbfg5210/HttpManager)中的 @Body 注解只能用于修饰实体数据类对象或者 Map,而 [Retrofit](https://github.com/square/retrofit) 中的则没有此限制。另外还有部分注解的内容也不尽相同。 接下来介绍一下使用方法: ### 引入依赖 #### Step 1. Add the JitPack repository to your build file ```gradle allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` #### Step 2. Add the dependency ```gradle dependencies { implementation 'com.gitee.cbfg5210:HttpManager:$version' } ``` ### 使用 ### Step 1. 初始化 [HttpManager](https://gitee.com/cbfg5210/HttpManager/blob/master/http/src/main/java/cbfg/http/HttpManager.kt) ```kotlin /** * @param okHttpClient 无论你对它设置了啥属性,传进来就行 * @param converterFactory 如果需要对请求参数进行加密或者添加请求 header 或者对请求结果进行解密的话要传入。默认实现可以查看 HttpManager.kt。 * @param gson 如果有自定义的 TypeAdapter 或者自定义的属性的话要传入,否则会使用默认的 */ fun init( okHttpClient: OkHttpClient, converterFactory: ConverterFactory? = null, gson: Gson? = null ) ``` ```kotlin HttpManager.init(okHttpClient) .setLogEnabled(BuildConfig.DEBUG) //log 开关 .putHost(GankService.TAG, GankService.URL) //配置 tag 对应的 host .putHost(WanService.TAG, WanService.URL) //配置 tag 对应的 host ``` ### Step 2. 创建接口 service 栗子一:[GankService.kt](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/gank/GankService.kt) ```kotlin @HostTag(GankService.TAG) interface GankService { @GET("/api/v2/categories/{category}") fun getSubCategories(@Path("category") parent: String): Observable>> @GET("/api/v2/data/category/{category}/type/{type}/page/{page}/count/{count}") fun getContentList( @Path("category") category: String, @Path("type") type: String, @Path("page") page: String, @Path("count") count: String ): Observable> @GET("/api/v2/data/category/{category}/type/{type}/page/{page}/count/{count}") fun getContentList2( @Path("category") category: String, @Path("type") type: String, @Path("page") page: String, @Path("count") count: String ): Observable } ``` 栗子二:[WanService.kt](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/wanandroid/WanService.kt) ```kotlin @HostTag(WanService.TAG) interface WanService { @POST("/user/register") @FormUrlEncoded fun register( @Field("username") username: String, @Field("password") password: String, @Field("repassword") repassword: String ): Observable @POST("/user/login") @FormUrlEncoded fun login( @Field("username") username: String, @Field("password") password: String, ): Observable @POST("/user/login") @FormUrlEncoded fun login(@Body account: Account): Observable @GET("/wxarticle/chapters/json") fun getOfficialAccounts(): Observable>> @GET("/wxarticle/list/{accountId}/{pageNum}/json") fun getAccountArticles( @Path("accountId") accountId: String, @Path("pageNum") pageNum: String ): Observable> @GET("/wxarticle/list/{accountId}/{pageNum}/json") fun getAccountArticles2( @Path("accountId") accountId: String, @Path("pageNum") pageNum: String ): Observable } ``` 先解释一下以上两个栗子再继续 Step 3 吧: ##### @HttpTag:可以用来标记对应的后台,如果不需要可以不加 ##### @HOST:标记这个 service 中对应的 base url,后续会改成动态配置获取的方式 ##### 请求结果:Observable ### Step 3. 执行请求 ```kotlin HttpManager.getService(GankService::class.java) .getContentList( spCategories.selectedItem.toString(), adapter.getItem(spSubCategories.selectedItemPosition).type, spPages.selectedItem.toString(), PAGE_LIMIT ) //.subscribeOn(ThreadMode.ASYNC) //默认 ThreadMode.ASYNC //.observeOn(ThreadMode.MAIN) //默认 ThreadMode.MAIN .subscribe(object : GankObserver>(lifecycle) { override fun onSubscribe(disposable: Disposable) { super.onSubscribe(disposable) tvResult.text = null } override fun onSuccess(result: BaseGankList) { tvResult.text = GsonHolder.gson.toJson(result) } override fun onError(e: Throwable) { tvResult.text = e.message } }) ``` 看着这个栗子是不是觉得像 [Retrofit](https://github.com/square/retrofit) + [RxJava](https://github.com/ReactiveX/RxJava) 的方式呀,确实像,但是没用 RxJava,而是参考了 [RxJava](https://github.com/ReactiveX/RxJava) 添加了3个类,具体见源码吧! ### 进阶 #### 1、自定义 ConverterFactory 如果项目中的请求需要进行加解密或者添加全局 header 的话,要自己实现 ConverterFactory,在初始化 HttpManager 的时候传入。 先看下 [ConverterFactory](https://gitee.com/cbfg5210/HttpManager/blob/master/http/src/main/java/cbfg/http/ConverterFactory.kt) 的长相吧: ```kotlin interface ConverterFactory { /** * 如果要对请求参数进行加密的话,在这个方法中进行 * @param hostTag @HostTag 中的 value * @param httpTag @HttpTag 中的 value * @param postType post 类型:json 数据提交、表单数据提交、 文件上传 * @param params 要提交的参数 */ fun convertRequestBody( hostTag: String?, httpTag: String?, postType: PostType, params: Map ): RequestBody /** * 如果想添加全局 header 的话,可以在这个方法中进行 */ fun convertRequest(hostTag: String?, httpTag: String?, request: Request): Request /** * 如果需要对请求结果进行解密的话,在这个方法中进行 */ @Throws(Exception::class) fun convertResponse(hostTag: String?, httpTag: String?, response: String): String } ``` 然后看下 HttpManager 中的默认实现: ```kotlin object : ConverterFactory { override fun convertRequest( hostTag: String?,httpTag: String?, request: Request): Request = request override fun convertResponse( hostTag: String?,httpTag: String?, response: String): String = response override fun convertRequestBody( hostTag: String?, httpTag: String?, postType: PostType, params: Map ): RequestBody { return PostBodyParser.parse(postType, params) } } ``` 对于参数的处理请见:[PostBodyParser](https://gitee.com/cbfg5210/HttpManager/blob/master/http/src/main/java/cbfg/http/util/PostBodyParser.kt),如果你要自定义 ConverterFactory 的话,可以参考这里的参数处理。 #### 2、自定义基础 Entity 类和基础 Observer 类 在 Step 3 中可以看到,在调用 subscribe(observer: Observer) 的时候要传入 Observer 对象,[Observer.kt](https://gitee.com/cbfg5210/HttpManager/blob/master/http/src/main/java/cbfg/http/subscribe/Observer.kt) 长这样: ```kotlin interface Observer { fun onSubscribe(disposable: Disposable) fun onNext(entity: T) fun onError(e: Throwable) fun onComplete() {} } ``` 看着很有 [RxJava](https://github.com/ReactiveX/RxJava) 的味道吧!回到正题,为什么要自定义基础 Entity 类和基础 Observer 类呢?当然是为了后续用的方便呀。这里说一下思路,自定义基础 Entity 除了添加基础属性外,可以对外提供一个判断是否成功的方法,基础 Observer 类根据这个方法决定执行onNext(x) 或者 onError(x),另外基础 Observer 中还可以封装处理 UI 生命周期事件,避免页面关闭造成内存泄露。自定义的 demo 可以看以下这里: Demo for 干货集中营: [BaseGankEntity](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/gank/entity/BaseGankEntity.kt) [BaseGankList](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/gank/entity/BaseGankList.kt) [GankObserver](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/gank/GankObserver.kt) Demo for WanAndroid: [BaseWanEntity](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/wanandroid/entity/BaseWanEntity.kt) [WanObserver](https://gitee.com/cbfg5210/HttpManager/blob/master/app/src/main/java/cbfg/http/demo/wanandroid/WanObserver.kt) #### 最后感谢[干货集中营](https://gank.io/)和[WanAndroid](https://www.wanandroid.com/)提供的 api!