2 Star 12 Fork 3

PineProject / QSHttp

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

QSHttp

QSHttp fastjson okhttp License

开箱即用,GET,POST,表单,JSON,上传,下载等等统统同一行代码搞定!
AIP精简到极致,调用没有一行多余代码,几乎零成本使用,大道至简

  • 5年实战环境验证迭代,稳定可靠
  • 强大灵活的入参,支持泛型回调,使用简单
  • 可简单实现自动弹加载框,判断业务状态码,弹错误提示
  • 支持多拦截器,可全局配置一些公共鉴权参数
  • 支持异步(回调已在主线程),同步请求
  • 支持自签名,双向https
  • 支持自定义有效时间缓存,错误缓存(联网失败时使用),缓存控制,cookie自动管理
  • 详细的请求信息回调、错误类型(网络链接失败,超时,断网,解析失败,404...)
  • 详细的访问日记打印,非常方便调试
  • 底层支持原生和okhttp

Gradle

//build.gradle
allprojects {
    repositories {
        maven {
            url "https://jitpack.io"
        }
    }
}

//app.gradle
dependencies {
    implementation 'com.github.tohodog:QSHttp:1.5.4'
}

最简单的例子

QSHttp.get("http://xxx").buildAndExecute();

HTTP调试地址

https://api.reol.top/api_test
可接受任何请求,该接口返回用户请求信息

初始化框架

        //初始化框架,调用一次即可,详细配置见#高级配置#
        QSHttp.init(getApplication());

GET

        String url = "https://api.reol.top/api_test";
        //使用泛型回调,自动解析json数据成模型
        QSHttp.get(url)
                .param("name", "QSHttp")
                .buildAndExecute(new QSHttpCallback<BaseModel<User>>() {
                    @Override
                    public void onComplete(BaseModel<User> bean) {
                        //请求解析成功,执行业务逻辑,BaseModel是接口返回数据通用模型
                    }
                    
                    //@Override//需要处理失败可覆盖
                    //public void onFailure(HttpException e) {
                    //    e.show();
                    //}
                });


        public class BeanModel<M> {
            public int status;
            public String msg;
            public M data;
        }

POST (application/x-www-form-urlencoded)

        String url = "https://api.reol.top/api_test";
        //使用原始回调
        QSHttp.post(url)
                .param("userName", 10086)
                .param("password", "qwe123456")
                .buildAndExecute(new HttpCallback() {
                    @Override
                    public void onSuccess(ResponseParams response) {
                        response.string();//响应内容
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        e.show();
                    }
                });

POST (application/json)

        String url = "https://api.reol.top/api_test";
        //不同类型请求只需改个方法名称即可实现
        QSHttp.postJSON(url)
                .param("userName", "song")
                .param("password", "123456")
                .buildAndExecute(new QSHttpCallback<Bean>() {
                    @Override
                    public void onComplete(Bean dataBean) {

                    }
                });

Download

        //基于get下载
        String url = "https://api.reol.top/api_test";
        QSHttp.download(url,"/sdcard/xxx.txt")
                .buildAndExecute(new HttpCallbackProgress() {
                    @Override
                    public void onProgress(long var1, long var2, String var3) {
                        long i = var1 * 100 / var2;//下载百分比
                    }

                    @Override
                    public void onSuccess(ResponseParams response) {
                        response.file();//获取目录
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        e.show();
                    }
                });

Upload (multipart/form-data)

        String url = "https://api.reol.top/api_test";
        QSHttp.upload(url)
                //文本参数
                .param("userName", 10086)
                .param("password", "qwe123456")
                //文件参数
                .param("file", new File("xx.jpg"))
                .param("bytes", new byte[1024])//上传一个字节数组
                //指定上传的文件名,content-type参数
                .multipartBody("icon", "image/*", "icon.jpg", new File("xx.jpg"))
                .multipartBody(new String("icon"), "image/*", "icon2.jpg", new byte[1024])//icon文件数组上传
                .buildAndExecute(new HttpCallbackProgress() {
                    @Override
                    public void onProgress(long rwLen, long allLen, String mark) {
                        int progress=rwLen * 100 / allLen ;//进度百分比,mark=参数名
                    }

                    @Override
                    public void onSuccess(ResponseParams response) {
                        response.string();//获取响应内容
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        e.show();
                    }
                });

实现一个自动弹出加载框,判断业务状态码的Callback

 在实际项目中,和后端交互JSON会有一套标准的格式,如{"status":0,"msg":"OK","data":{}}, 每个请求都判断太过于麻烦,而且也不方便统一处理,下面就实现一个用起来非常愉悦的回调:

public abstract class MyHttpCallback<T> extends QSHttpCallback<T> {

    protected boolean isShow = true;

    public MyHttpCallback() {
        super();
    }

    //在Activity/Fragment/view里调用QSHTTP可不传入context,会自动反射获取
    public MyHttpCallback(boolean isShow) {
        this.isShow = isShow;
    }

    public MyHttpCallback(Activity activity, boolean isShow) {
        super(activity);
        this.isShow = isShow;
    }

    @Override//这里开发者根据自己的情况修改键值即可
    public T map(String response) throws HttpException {
        JSONObject jsonObject = JSON.parseObject(response);
        //服务器状态码不对
        if (jsonObject.getIntValue("status") != 0) {
            throw HttpException.Custom(jsonObject.getString("msg"), jsonObject);
        }
        //这里可以继续加统一的处理代码,如登录失效
        
        return parserT(jsonObject.getString("data"));
    }


    @Override
    public void onFailure(HttpException e) {
        if (activity != null) Toast.makeText(activity, e.getPrompt(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart() {
        showProgressDialog(false);
    }

    @CallSuper
    @Override
    public void onEnd() {
        dismissProgressDialog();
    }


    protected ProgressDialog mDialog;

    /**
     * 用于显示Dialog
     */
    protected void showProgressDialog(boolean mCancelable) {
        if (isShow && mDialog == null && activity != null && !activity.isFinishing()) {
            mDialog = new ProgressDialog(activity);
            mDialog.setCancelable(mCancelable);
            if (mCancelable) {
                mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                    }
                });
            }
            mDialog.show();
        }
    }

    protected void dismissProgressDialog() {
        if (isShow && mDialog != null && activity != null && !activity.isFinishing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

}

高级配置

        //混淆
        -keep class * extends org.song.http.** { *; }

        //使用配置初始化,全局参数
        QSHttp.init(QSHttpConfig.Build(getApplication())
                //请求host,智能拼接请求地址
                .baseUrl("http://reol.top/api")

                //配置需要签名的网站, 读取assets/cers文件夹里的.cer证书
                //支持双向认证,只需放入xxx.bks,见demo
                .ssl(Utils.getAssetsSocketFactory(this, "cers", "password")
                        , "192.168.1.168")//host参数:设置需要自签名的主机地址,不设置则只能访问.cer证书列表里的https网站
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())//证书信任规则(全信任)

                .cacheSize(128 * 1024 * 1024)
                .connectTimeout(18 * 1000)
                .debug(true)//打印日记

                //拦截器 全局添加头参数 鉴权
                .interceptor(interceptor)
                .build());

        //拦截器
        static Interceptor interceptor = new Interceptor() {
                @Override
                public ResponseParams intercept(Chain chain) throws HttpException {
                    RequestParams r = chain.request()
                            .newBuild()
                            .header("Interceptor", "Interceptor")//全局头参数
                            //继续添加修改其他
                            .build();
                    return chain.proceed(r);//请求结果参数如有需要也可以进行修改
                }
            };
         
        //添加不同配置的client,满足不同需求
        QSHttp.addClient("test", QSHttpConfig.Build(getApplication())
                .xxHttp(HttpEnum.XX_Http.JAVA_HTTP)//使用原生底层实现
                .cacheSize(128 * 1024 * 1024)
                .connectTimeout(10 * 1000)
                .debug(true)
                .build());
        QSHttp.get("url").qsClient("test").buildAndExecute();//该请求将使用上述的配置

所有API一览

        String url = "https://api.reol.top/api_test";
        //同步请求
        Future<ResponseParams> future = QSHttp.get(url).param("future", "future").buildAndExecute();
        ResponseParams res = future.get();//get阻塞

        QSHttp.post(url)//选择请求的类型
                .header("User-Agent", "QsHttp/Android")//添加请求头

                .path(2333, "video")//构建成这样的url https://api.reol.top/api_test/2233/video

                .param("userName", 123456)//键值对参数
                .param("password", "asdfgh")//键值对参数
                .param(new Bean())//键值对参数
                .param("bytes", new byte[1024])//传一个字节数组,multipart支持此参数
                .param("file", new File("xx.jpg"))//传一个文件,multipart支持此参数

                .jsonBody(new Bean())//传入一个对象,会自动转化为json上传;application/json
                //自定义Body的内容 自定义contentType (postjson内部是调用这个实现)
                .requestBody("image/jpeg", new File("xx.jpg"))

                .parser(parser)//自定义解析,由自己写解析逻辑
                .resultByBytes()//请求结果返回一个字节组 默认是返回字符
                .resultByFile(".../1.txt")//本地路径 有此参数 请求的内容将被写入文件

                .errCache()//开启这个 [联网失败]会使用缓存,如果有的话
                .timeOut(10 * 1000)//单独设置超时
                .openServerCache()//开启服务器缓存规则 基于okhttp支持
                .clientCache(24 * 3600)//开启强制缓存,一天内都不会请求了
                .charset("utf-8")//特殊需求可以更改编码
                .tag("no token")//可配合拦截器使用
                //执行联网
                .buildAndExecute(new HttpCallbackEx() {

                    @Override
                    public void onStart() {
                        //开始请求
                    }

                    @Override
                    public void onSuccess(ResponseParams response) {
                        response.string();//获得响应字符串 *默认
                        response.file();//设置了下载 获得路径
                        response.bytes();//设置了返回字节组 获得字节组

                        response.headers();//获得响应头

                        //获得解析的模型
                        Bean b = response.jsonModel(Bean.class);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        e.show();//弹出错误提示 网络连接失败 超时 404 解析失败 ...等
                        String response = (String) e.getExObject();//可获取非200异常的参数
                    }

                    @Override
                    public void onEnd() {
                        //结束请求
                    }


                    @Override
                    public boolean isDestroy() {
                        return isFinishing();//页面关闭不会回调
                    }
                });

Log

v1.5.4(2020-12-15)

  • 支持baseUrl
  • 更新依赖
  • 优化

v1.5.3(2020-11-27)

  • 支持同步
  • 优化监听回调,url兼容性

v1.5.1(2020-07-03)

  • 支持多网络同时访问(在打开WIFI情况下访问蜂窝网络)
  • 优化

v1.5.0(2019-12-19)

  • 支持多拦截器
  • 支持multipart数组上传

Other

  • 有问题请Add issues
  • 如果项目对你有帮助的话欢迎 star
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 2017 蔡小路 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.

简介

开箱即用的Android安卓http/https网络框架,GET、POST、表单、JSON、上传、下载等等通通同一行代码搞定! 展开 收起
Android
Apache-2.0
取消

发行版 (4)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Android
1
https://gitee.com/sakaue/QSHttp.git
git@gitee.com:sakaue/QSHttp.git
sakaue
QSHttp
QSHttp
master

搜索帮助