1 Star 1 Fork 202

软件测试相关 / easy-okhttp

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

easy-okhttp

==============

Maven Central License

Java网络框架的另一种选择

============== easy-okhttp是Java网络框架,简化网络操作,专注于业务处理

文档目录(点击快速导航)

** 在GITOSC下不生效 **

新版介绍

easy-okhttp框架逐渐走向成熟,1.0.0-Final是框架的第一个Release包,当然后面还会继续更新。下面简单介绍1.0.0-Final的特性。

  • 大部分代码进行了重构;
  • okhttp3gson,mzlion-core依赖包更新至最新版;
  • 简化POST提交的使用(合并了CommonPostRequest和FormDataPostRequest);
  • OkHttpClient实现全局单例,节省创建OkHttpClient耗时;
  • 对HTTPS支持单向认证和双向认证;
  • 增加数据转换接口,统一数据处理;
  • 支持同步请求和异步请求;
  • 对于请求失败的信息更为详细;
  • 代码注释更为详细;

简介

easy-okhttp是对okhttp3网络框架封装,提供文件上传和下载,表单(含文件)提交,链式调用,支持HTTPS和自定义签名证书等特性。 okhttp3网络框架的流行始于Android,但是在Java后端仍然是Apache HttpClient网络框架,这个框架的缺点在于设计非常的复杂,而且jar的比较大。 所以才有easy-okhttp项目,主要目的希望弃用Apache HttpClient,其次也是为了帮助okhttp的推广^_^。

PS:本人Java技术不断成长中,所以项目难免存在bug。当出现问题时,请大家把问题共享出来,我会尽快处理,抑或我们一起讨论也可以的。 共享自己碰到的问题,方便你我他,也使得这个项目就会更加的富有生命力,谢谢! 当然也希望大家star和fork,同时非常欢迎大家参与项目的开发。

依赖说明

  • okhttp,本项目核心所在,底层依赖了okio框架,框架的大小在500Kb之内
  • mzlion-core,项目依赖的工具类,底层依赖了slf4j-apigson两个框架,框架的大小在400Kb之内

也就是说easy-okhttp整个包的大小在1M左右,相对于Apache HttpClient体积非常的小,而且使用也更为方便。

联系方式

  • 邮箱地址 mzllon@qq.com
  • QQ群 喜大奔普,QQ群建立啦:QQ群加入
  • 建议使用QQ群,邮箱使用较少,可能看的不及时
  • 本QQ群的目前范围不仅仅讨论该项目,同时也支持Java、Intellij IDEA等问题交流,欢迎大家入群。

框架引入

maven

<dependency>
    <groupId>com.mzlion</groupId>
    <artifactId>easy-okhttp</artifactId>
    <version>1.0.0-Final</version>
</dependency>

Gradle

compile 'com.mzlion:easy-okhttp:1.0.0-Final'

下载jar

框架特性说明

  • 支持GET和POST请求
  • 基于POST的大文本数据、二进制文件上传,即通过Http Body提交
  • 普通的表单提交
  • 带有文件表单提交
  • 表单提交支持参数名重复,即在后台接收到的是数组或集合
  • 支持session保持
  • 支持链式调用
  • 支持可信任证书和自定义签名证书的https访问
  • 注释详细,并且提供了demo
  • 增加异步请求的支持
  • 提供数据处理器,轻松将数据转为自己想要的结果
  • 更多特性增加中

全局配置

框架会自动读取classpath下的easy-okhttp.properties配置文件,如果没有特别的要求话,一般不需要重载该配置文件。

  • easy-okhttp.properties配置文件的配置信息
    • connectTimeout 连接超时时间,默认设置10秒
    • readTimeout 内容读取超时时间,默认是30秒
    • writeTimeout 内容写入超时时间,默认30秒
    • 支持设置公共header,规则如下 以header开头的表示设置公共请求头,header.之后就是键名,等号之后的键对应的值 #header.partner = MZ2017 #则表示往header塞一对键值 partner=MZ2017
  • 如果需要更改这些默认配置,有两种方式
    • 覆盖框架提供的配置easy-okhttp.properties,框架优先加载项目中的配置文件,超时时间的单位都是毫秒
    • 通过代码设置全局配置
  • 通过代码也可以设置全局参数,该配置操作只需要操作一次,因而可以放在项目启动时配置。
    • 设置连接超时时间 HttpClient.Instance.setConnectTimeout(int)
    • 设置读取超时时间 HttpClient.Instance.setReadTimeout(int)
    • 设置写入超时时间 HttpClient.Instance.writeTimeout(int)
    • 设置自定义签名证书 HttpClient.Instance.https(?)
    • 设置默认Header HttpClient.Instance.setDefaultHeader(?)
  • SSL证书配置 2017年马上就要到来,SSL在2017使用率更加高,所以这边跟紧步骤,增加了HTTPS单向认证和双向认证。HTTPS全局配置需要通过代码设置。
    • 网站启用了HTTPS,但SSL由信任的Root CA发布的,那么框架自动信信任,不需要你做任何配置
    • 信任任何一个网站,这个时候HTTPS形同虚设,客户端根本不鸟这些 HttpClient.Instance.https()
    • 假如使用的自签证书(经典的12306)或系统不能自动信任的SSL证书(Let's Encrypt) HttpClient.Instance.https(HttpClient.class.getClassLoader().getResourceAsStream("mzlion_com.cer"))
    • 最严格就是双向认证 HttpClient.Instance.https(InputStream pfxStream, char[] pfxPwd, InputStream... certificates)

基本示例

1.普通的GET请求无参数

    String responseData = HttpClient
                // 请求方式和请求url
                .get("http://localhost:8080/user-sys/user/list") 
                .execute()
                .asString();

2.普通的GET请求带参数

    String responseData = HttpClient
                // 请求方式和请求url
                .get("http://localhost:8080/user-sys/user/list")
                //设置请求参数
                .queryString("mobile","18018110018")   
                .execute()
                .asString();

3.POST普通表单提交

    String responseData = HttpClient
                // 请求方式和请求url
                .post("http://localhost:8080/user-sys/user/add")                               
                // 表单参数
                .param("name","张三")  
                .param("mobile", "13023614020")
                .param("langs", "Java")
                .param("langs", "Python")
                //url参数
                //queryString("queryTime","20160530") 
                .execute()
                .asString();

上传大文本数据、JSON类型的文本、大文件等

一般针对POST提交数据内容较为复杂、接口约定需要POST上传时调用本方法非常有效。这种提交方式也是POST,但是数据内容和格式直接写入请求流中。比如微信接口就是这种模式。

1.POST提交String

    String responseData = HttpClient
                // 请求方式和请求url
                .textBody("http://localhost:8080/user-sys/user/body1")                               
                .text("设施一串和服务端约定好的数据格式")
                //设置编码
                //.charset("utf-8")
                .execute()
                .asString();

2.POST提交JSON格式的文本

    String responseData = HttpClient
                // 请求方式和请求url
                .textBody("http://localhost:8080/user-sys/user/import")                               
                // post提交json
                .json("[{\"name\": \"test-13\",\"mobile\": \"18321001200\",\"programLangs\": \"Java,Pyhton\",\"remark\": \"0\"}]")
                //post提交xml
                //.xml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>") 
                //post提交html
                //.html("function fun(){}")
                //.charset("utf-8")
                //设置编码
                .execute()
                .asString();

3.POST提交XML等其他格式的文本

    String responseData = HttpClient
                // 请求方式和请求url
                .textBody("http://localhost:8080/user-sys/user/body2")                               
                //post提交xml
                .xml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>") 
                //post提交html
                //.html("function fun(){}")
                //post提交一段javascript
                //.javascript("function fn(){}")
                //设置编码
                //.charset("utf-8")
                .execute()
                .asString();

4.POST提交二进制文件

    String responseData = HttpClient
                // 请求方式和请求url
                .binaryBody("http://localhost:8080/user-sys/user/body3")                               
                // post提交流
                .stream(this.getClass().getClassLoader().getResourceAsStream("avatar.png"))
                //设置请求内容类型
                .contentType(ContentType.IMAGE_JPG)
                //post提交文件
                //.file(new File("d:/avatar.png")) 
                .execute()
                .asString();
//ContentType内置常见的MIME类型,基本上不用自己创建

表单提交、一参数多值

1.POST表单提交含文件上传

    String responseData = HttpClient
                // 请求方式和请求url
                .post("http://localhost:8080/user-sys/user/add")                               
                .param("name", "李四")
                .param("mobile", "13023614021")
                .param("avatarFile", this.getClassLoader().getResourceAsStream("avatar.png"), "avatar.png")
                //.param("avatarFile", new File("D:/avatar.png")
                .execute()
                .asString();

2.POST提交支持一个参数设置多个值或替换

    String responseData = HttpClient
                // 请求方式和请求url
                .post("http://localhost:8080/user-sys/user/add")                               
                // 表单参数
                .param("name","张三")  
                .param("mobile", "13023614020")
                .param("langs", "Java")
                .param("langs", "Python")//会多种语言
                .execute()
                .asString();

HttpResponse对象介绍

以上展示的代码都是基于同步请求的,并且你会发现示例代码中总是出现asString()方法,这个方法来自HttpResponse类,该类是对服务端相应数据的封装, 下面就详细介绍下该类的功能特色。

  1. HttpResponse.isSuccess()表示请求是否成功,只有请求成功才会有后面的功能。
  2. HttpResponse.getErrorMessage 请求失败时错误消息。
  3. 当请求执行完成之后推荐调用HttpResponse.isSuccess()判断请求成功还是失败,如果没有进行判断且请求失败则会抛出异常HttpStatusCodeException

下面就是非常好用的方法

  1. public String asString() 将响应结果直接转为字符串
  2. public <E> E asBean(Class<E> targetClass) 将响应结果转为JavaBean
  3. public <E> E asBean(TypeRef<E> typeRef) 也是将响应结果转为JavaBean,和上面的区别在于该方法能够提取到泛型信息
  4. public byte[] asByteData() 将响应结果转为二进制内容,这是数据在网络请求的原始数据
  5. public void asFile(File saveFile) 将响应结果转为文件存储,当远程是文件时该方法非常有用
  6. public void asStream(OutputStream out) 直接将响应结果输出到另外一个流中
  7. public <T> T custom(DataHandler<T> dataHandler) 当以上这些方法都满足不了你的话,这个方法可以自己DIY,随你怎么蹂躏

下面给出一些简单的代码,这些方法已经非常简单了。

    //将响应结果转为字符串输出
    String responseData = httpResponse.asString();
    
    //将响应结果转为文件保存
    File frc = new File("d:\\web\\save.txt");
    httpResponse.asFile(frc);

    //json转换器
    List<Person> personList = httpResponse.asBean(new TypeToken<List<Person>>(){});
    //重载方法
    //Person person = httpResponse.asBean(Person.class);

    //将响应结果转为输出流中
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    httpResponse.asStream(baos);

HTTPS

前面已经提到HTTPS的配置,下面给出一些简单的示例更直观了解用法。

    //由信任CA机构发布的,比如GitHub的https,框架不需要你做什么事情,正常使用即可
    String githubContent = HttpClient
        .get("https://www.github.com")
        .execute()
        .asString();

    //不管三七二十几,直接信任了所有请求
    String mzlionIndexContent = HttpClient
        .get("https://kyfw.12306.cn/otn/")
        .https()
        .execute()
        .asString();
    
    //自签SSL或程序不认可实际安全的,可以指定客户端证书
    String mzlionIndexContent = HttpClient
        .get("https://kyfw.12306.cn/otn/")
        .https(this.getClass().getClassLoader().getResourceAsStream("SRCA.cer"))
        .execute()
        .asString();
    

数据处理器DataHandler

这是新版本的新增的一个功能,数据处理器定义接口返回数据处理能力,该接口就只有一个函数

    T handle(final okhttp3.Response response) throws IOException;

该函数提供了将原始数据格式转为业务所需数据格式,框架提供了常用接口处理器实现,若以下的处理器无法满足需求可以自己实现一个处理器。

  • StringDataHandler 字符串处理器,该处理器比较常用,可以直接调用StringDataHandler.create()得到处理器的实例
  • JsonDataHandler<T> JSON处理器,该处理器也比较常用,即将JSON字符串转为Javabean
  • FileDataHandler 文件处理器,将结果存储到文件中,该处理器有两个构造参数,其中dirPath保存目录必填,filename保存的文件名可选,如果为空时框架自动从header、url中获取,如果获取不到则随机生成一个文件名。

高级配置

异步请求

异步请求不会阻塞当前线程(特别是网络慢的时候),适用于对返回结果不关心或不需要立即知晓的情况下,比如推送、通知等。 异步请求只有在执行网络请求的时候有一点区别,其他地方和同步请求配置和操作都是一样的。

    String githubContent = HttpClient
            .get("https://www.github.com")
            .execute(new CallbackAdaptor<String>(){
                
                @Override
                public DataHandler<T> getDataHandler() {
                    return StringDataHandler.create();
                }
            
                @Override
                public void onSuccess(T data) {
                    //data就是经过处理后的数据,直接在这里写自己的业务逻辑
                }
            });

Callback回调接口

Callback是回调定义接口,里面总共定义了6个函数,每个函数被调用的顺序不一样。

  • onBefore() 第一被调用,主要在请求网络之前,这个函数有返回值,如果返回false则阻止此次请求了;
  • postProgress() 第二被调用,上传进度回调函数
  • onError() 第三被调用,当只有请求失败时才会触发;
  • onComplete() 第四被调用,当请求接口完成后触发该函数;
  • onSuccess() 第五被调用,当请求接口成功(HTTP状态码为200)则会触发该函数, 该函数会依赖另外一个函数getDataHandler(),返回一个指定的数据处理器,处理原始数据。对于数据处理器前面已经了解过了。

异步回调接口Callback总共定义了6个函数,但是一般不会关心所有函数处理情况,所以提供了CallbackAdaptor空实现类,想要关注哪个函数的执行结果,重载那个函数即可。

为单个请求设置超时

当我们需要对单个请求设置连接超时时间、读取超时时间等属性时,可以在执行execute方法之前调用。主要有如下几个方法可以进行调用。

  • connectTimeout(int) 连接超时时间
  • readTimeout(int) 读取超时时间
  • writeTimeout(int) 写入超时时间
  • https() 设置https证书

一般一个项目只请求一个远程服务,所以这些配置可以在全局配置,共享一个OkHttpClient对象(相当于共享一个浏览器),以上这些方法的调用会使得框架创建一个新的OkHttpClient对象(相当于又打开了一个浏览器)。下面给出一个snippet加以说明。

    //字符串转换器
    String responseData = HttpClient
                //设置请求方式
                .get()    
                //设置请求地址
                .url("http://localhost:8080/user-sys/user/find_by_mobile")   
                //设置请求参数
                .queryString("mobile","18118181234")  
                //覆盖设置,读取超时时间
                .readTimeout(30000)     
                //执行
                .execute()            
                .asString();

关于demo

目前Demo已完成,使用SpringBoot开发,数据库用的是H2。目前仅仅实现了用户的增删改查功能,可以用来学习SpringBoot和easy-okhttp。 项目地址:easy-okhttp-test-server

老版本V1.0.4的文档在这里

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: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and 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 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 find 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.

简介

这是一个对okhttp3进行封装的工具,提供了更为便捷的方法调用。目的是为了替换难用的apache HttpClient。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/software_testing_related/easy-okhttp.git
git@gitee.com:software_testing_related/easy-okhttp.git
software_testing_related
easy-okhttp
easy-okhttp
master

搜索帮助