6 Star 16 Fork 4

HarmonyOS-TPC / okhttp-OkGo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

一个基于okhttp的标准RESTful风格的网络框架

工程结构全新优化
支持RxJava
支持RxJava2
支持自定义缓存策略 支持下载管理
支持上传管理

集成配置

方法一:

按需以module方式导入okgo,okrx,okrx2,okserver中的一个或者多个module到自己鸿蒙项目中;并使用下面的方式依赖
     implementation project(':okgo')
     implementation project(':okrx')
     implementation project(':okrx2')
     implementation project(':okserver') 
另外okgo基础module中必须添加ohos.jar的依赖,否则编译不通过,格式如下所示:
api files('D:\\HOSDEMO\\ohosjar\\ohos.jar')
意味着需要把SDK中的ohos.jar复制出来到D盘后,将上述路径更换为你的ohos.jar的实际本地路径

方法二:

编译module生成jar放进libs中
步骤:点击右侧gradle,选择对应的module;比如okgo,然后点击Tasks展开,再点击jar即生成;
     生成的jar包在对应的module下面的build\libs中
引入:将生成jar包放入对应entry或者module的libs目录中

方法三

添加中心仓库
allprojects{
    repositories{
        mavenCentral()
    }
}
按照需要添加如下依赖配置
implementation 'io.openharmony.tpc.thirdlib:okgo:1.0.2' 
implementation 'io.openharmony.tpc.thirdlib:okrx:1.0.2' 
implementation 'io.openharmony.tpc.thirdlib:okrx2:1.0.2' 
implementation 'io.openharmony.tpc.thirdlib:okserver:1.0.2' 

jar包使用注意事项

使用 okgo.jar必须自行依赖okhttp3
使用 okrx.jar需依赖rxjava库
使用 okrx2.jar需依赖rxjava2
具体三方库版本见entry的依赖配置

不要忘记在你的entry的config.json中添加网络权限(其他初始化配置见entry的OkGoApp.java)

"reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]

OkGo主要功能

基本的get、post、put、delete、head、options、trace、patch八种请求
支持upString,upJson,upBytes,upFile等up类方法上传特定数据
支持一个key上传一个文件,也可以一个key上传多个文件,也可以多文件和多参数一起上传
大文件下载和下载进度回调
大文件上传和上传进度回调
支持cookie的自动管理,并可自定义cookie管理策略
支持缓存模式,不仅支持http缓存协议,也支持自定义缓存策略
支持重定向
支持自定义超时自动重连次数
支持链式调用
支持https访问,支持双向认证
支持根据tag取消请求,也可全部取消
支持自定义Callback,自动解析网络数据

1.请求所有配置

重要的事情说三遍
无论做什么请求,第一行的泛型一定要加!!!

注意以下几点:

这里演示的是一次普通请求所有能配置的参数,真实使用时不需要配置这么多,按自己的需要选择性的使用即可
第一行的泛型一定要特别注意,这个表示你请求网络的数据类型是什么,必须指定,否则无法解析网络数据。
.post(url):这个表示当前请求是post请求,当然一共支持GET,HEAD,OPTIONS,POST,PUT,DELETE, PATCH, TRACE这8种请求方式,
 你只需要改改这个方法名就行了,很方便。
.params():添加参数的时候,最后一个isReplace为可选参数,默认为true,即代表相同key的时候,后添加的会覆盖先前添加的。
.tag(this):请求的tag,用于标识当前的请求,方便后续取消对应的请求,如果你不需要取消请求,也可以不用设置。
.isMultipart():该方法表示是否强制使用multipart/form-data表单上传,因为该框架在有文件的时候,无论你是否设置这个参数,
 默认都是multipart/form-data格式上传,但是如果参数中不包含文件,默认使用application/x-www-form-urlencoded格式上传,
 如果你的服务器要求无论是否有文件,都要使用表单上传,那么可以用这个参数设置为true。
.isSpliceUrl():该方法表示是否强制将params的参数拼接到url后面,默认false不拼接。一般来说,post、put等有请求体的方法应该把参数都放在请求体中,
 不应该放在url上,但是有的服务端可能不太规范,url和请求体都需要传递参数,那么这时候就使用该参数,他会将你所有使用.params()方法传递的参数,自动拼接在url后面。
.retryCount():该方法是配置超时重连次数,也可以在全局初始化的时候设置,默认使用全局的配置,即为3次,你也可以在这里为你的这个请求特殊配置一个,
 并不会影响全局其他请求的超时重连次数。
.cacheKey() .cacheTime() .cacheMode():这三个是缓存相关的配置,详细请看缓存介绍
.headers():该方法是传递服务端需要的请求头,如果你不知道什么是请求头,看wiki首页关于网络抓包中的http协议链接。
.params():该方法传递键值对参数,格式也是http协议中的格式,详细参考上面的http协议连接。
.addUrlParams() .addFileParams() .addFileWrapperParams():这里是支持一个key传递多个文本参数,也支持一个key传递多个文件参数,详细也看上面的http协议连接。
 另外,每个请求都有一个.client()方法可以传递一个OkHttpClient对象,表示当前这个请求将使用外界传入的这个OkHttpClient对象,其他的请求还是使用全局的保持不变。
 那么至于这个OkHttpClient你想怎么配置,或者配置什么东西,那就随意了是不,改个超时时间,加个拦截器什么的统统都是可以的,看你心情喽。

特别注意: 如果你的当前请求使用的是你传递的OkHttpClient对象的话,那么当你调用OkGo.getInstance().cancelTag(tag)的时候,是取消不了这个请求的,因为OkGo只能取消使用全局配置的请求,不知道你这个请求是用你自己的OkHttpClient的,如果一定要取消,可以是使用OkGo提供的重载方法,详细看下方的取消请求的部分。

2.Response对象介绍


先看Response对象内部的字段:  该对象一共有5个字段,分别表示以下意思:

body:当前返回的数据,T即为数据的泛型。使用方法body()获取该值。如果请求成功,回调onSuccess(),该字段为convertResponse()解析数据后返回的数据。如果发生异常,回调onError(),该字段值为null。
throwable:如果发生异常,回调onError(),该字段保存了当前的异常信息。如果请求成功,回调onSuccess(),该字段为null。使用方法getException()获取该值。
isFromCache:表示当前的数据是来自哪里,true:来自缓存,false:来自网络。使用方法isFromCache()获取该值。
rawCall:表示当前请求的真正okhttp3.Call对象。使用方法getRawCall()获取该值。
rawResponse:表示当前请求服务端真正返回的okhttp3.Response对象,注意:如果数据来自缓存,该对象为null,如果来自网络,该对象才有值。使用方法getRawResponse()获取该值。
另外,该对象还有以下几个方法:

code():http协议的响应状态码,如果数据来自网络,无论成功失败,该值都为真实的响应码,如果数据来自缓存,该值一直为-1。
message():http协议对响应状态码的描述信息,如果数据来自网络,无论成功失败,该值都为真实的描述信息,如果数据来自缓存,该值一直为null。
headers():服务端返回的响应头信息,如果数据来自网络,无论成功失败,该值都为真实的头信息,如果数据来自缓存,该值一直为null。
isSuccessful():本次请求是否成功,判断依据是是否发生了异常。

3.基本请求

重要的事情说三遍
无论做什么请求,第一行的泛型一定要加!!!

那么我们不可能每次请求都写上面那么一大堆,这里可以看到,一次简单的请求,这么写就够了。 

4.请求Bitmap
如果你知道你的请求数据是图片,可以使用这样的方法 

5.基本文件下载
如果你要下载文件,可以这么写。

FileCallback具有三个重载的构造方法,分别是

FileCallback():空参构造
FileCallback(String destFileName):可以额外指定文件下载完成后的文件名
FileCallback(String destFileDir, String destFileName):可以额外指定文件的下载目录和下载完成后的文件名

文件目录如果不指定,默认下载的目录为 sdcard/download/,文件名如果不指定,则按照以下规则命名:

1.首先检查用户是否传入了文件名,如果传入,将以用户传入的文件名命名
2.如果没有传入,那么将会检查服务端返回的响应头是否含有Content-Disposition=attachment;filename=FileName.txt该种形式的响应头,如果有,则按照该响应头中指定的文件名命名文件,如FileName.txt
3.如果上述响应头不存在,则检查下载的文件url,例如:http://image.baidu.com/abc.jpg,那么将会自动以abc.jpg命名文件
4.如果url也把文件名解析不出来,那么最终将以"unknownfile_" + System.currentTimeMillis()命名文件

这里面有个新对象叫Progress,关于这个对象的解释,看这里我进行了专门的讲解。



6.上传String类型的文本
一般此种用法用于与服务器约定的数据格式,当使用该方法时,params中的参数设置是无效的,所有参数均需要通过需要上传的文本中指定,此外,额外指定的header参数仍然保持有效。

默认会携带以下请求头

Content-Type: text/plain;charset=utf-8

如果你对请求头有自己的要求,可以使用这个重载的形式,传入自定义的content-type

// 比如上传xml数据,这里就可以自己指定请求头 upString("这是要上传的长文本数据!", MediaType.parse("application/xml"))



7.上传JSON类型的文本
该方法与upString没有本质区别,只是数据格式是json,一般来说,需要自己创建一个实体bean或者一个map,把需要的参数设置进去,然后通过三方的Gson或者fastjson转换成json对象,最后直接使用该方法提交到服务器。

默认会携带以下请求头,请不要手动修改,okgo也不支持自己修改

Content-Type: application/json;charset=utf-8



8.上传文件
上传文件支持文件与参数一起同时上传,也支持一个key上传多个文件,以下方式可以任选

特别要注意的是

1). 很多人会说需要在上传文件到时候,要把Content-Type修改掉,变成multipart/form-data,就像下面这样的。其实在使用OkGo的时候,只要你添加了文件,
    这里的的Content-Type不需要你手动设置,OkGo自动添加该请求头,同时,OkGo也不允许你修改该请求头。
    Content-Type: multipart/form-data; boundary=f6b76bad-0345-4337-b7d8-b362cb1f9949

2). 如果没有文件,那么OkGo将自动使用以下请求头,同样OkGo也不允许你修改该请求头。
Content-Type: application/x-www-form-urlencoded

3). 如果你的服务器希望你在没有文件的时候依然使用multipart/form-data请求,那么可以使用.isMultipart(true)这个方法强制修改,一般来说是不需要强制的。


有人说他有很多文件,不知道数量,又要一个文件对应一个key该怎么办,其实很简单,把调用链断开,用循环添加就行了嘛。 

9.取消请求
  之前讲到,我们为每个请求前都设置了一个参数tag,取消就是通过这个tag来取消的。通常我们在Activity中做网络请求,当Activity销毁时要取消请求否则会发生内存泄露,
  那么就可以在onDestory()里面写如下代码:

注意以下取消的请求不要全部用,自己按需要写,我只是写出来,告诉你有这么几个方法。 

10.同步请求
   同步请求有两种方式,第一种是返回原始的Response对象,自行解析网络数据,就像这样: 

   或者可以返回解析解析完成的对象,如果你使用过Retrofit,那么你对这个Call对象一定不会陌生,这里面有个方法是converter(),需要传递一个Converter接口,
   作用其实就是解析网络返回的数据,你也可以自定义Converter代码如下: 

11. https请求
https的请求和http请求一模一样,只需要在初始化配置一下,详细的https配置方法点击这里。

12.参数的顺序
添加headers和params的方法各有三处,在提交的时候,他们是有顺序的,如果对提交顺序有需要的话,请注意这里

第一个地方,全局初始化时添加 

第二个地方,Callback的onStart()方法中添加 

第三个地方,执行网络请求的时候添加 

那么,最终执行请求的参数的添加顺序为

Header顺序: HKAAA -> HKBBB -> HKEEE -> HKFFF -> HKCCC -> HKDDD
Params顺序: PKAAA -> PKBBB -> PKEEE -> PKFFF -> PKCCC -> PKDDD

混淆

okgo, okrx, okrx2, okserver 所有代码均可以混淆,但是由于底层使用的是 okhttp,它不能混淆,所以只需要添加以下混淆代码就可以了

#okhttp
-dontwarn okhttp3.**
-keep class okhttp3.**{*;}

#okio
-dontwarn okio.**
-keep class okio.**{*;}

当然如果你确实不需要混淆okgo的代码,可以继续添加以下代码

#okgo
-dontwarn com.lzy.okgo.**
-keep class com.lzy.okgo.**{*;}

#okrx
-dontwarn com.lzy.okrx.**
-keep class com.lzy.okrx.**{*;}

#okrx2
-dontwarn com.lzy.okrx2.**
-keep class com.lzy.okrx2.**{*;}

#okserver
-dontwarn com.lzy.okserver.**
-keep class com.lzy.okserver.**{*;}

Licenses

 Copyright 2016 jeasonlzy(廖子尧)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016 jeasonlzy(廖子尧) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

一个基于okhttp的标准RESTful风格的网络框架 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/HarmonyOS-tpc/okhttp-OkGo.git
git@gitee.com:HarmonyOS-tpc/okhttp-OkGo.git
HarmonyOS-tpc
okhttp-OkGo
okhttp-OkGo
master

搜索帮助