• Stars
    star
    441
  • Rank 98,861 (Top 2 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

OkHttp封装,支持GET、POST、UI线程回调、JSON格式解析、链式调用、小文件上传下载及进度监听等功能

#OkHttpPlus

OkHttpPlus is a tool for OkHttp


OkHttpPlus是OkHttp的一个工具类,主要对Get和Post方法进行了简单封装,所有方法的回调都在UI线程完成,内置了String、JsonObject、JsonArray数据类型的解析器,封装了对小文件下载和文件上传功能,可以实现进度监听,使之满足常见的Http需求。

如果满足不了你的需求,请发issuse。

中文文档请戳这里

##Features

  • More simple use for GET and POST
  • CallBack run on the UI Thread
  • Support small size file download and upload without other library
  • Build in support for JSON Object and JSON Array parse

##Update

  • Add sync method,enqueue is Async Method,execute is Sync Method

##Sample Usage

###Init OkHttpClient First , you can init the OkHttpClient as usual

public class OkApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        OkHttpClient okHttpClient = OkHttpProxy.getInstance();
        okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(15, TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(15, TimeUnit.SECONDS);    }
}

###Get JSON Object And JSON Array

Use OkJsonParser ,you could get a User Object form json format string.

OkHttpProxy.get()
                .url(URL_USER)
                .tag(this)
                .enqueue(new OkCallback<User>(new OkJsonParser<User>() {
                }) {
                    @Override
                    public void onSuccess(int code, User user) {
                        tv_response.setText(user.toString());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        tv_response.setText(e.getMessage());
                    }
                });

Use OkJsonParser<List> ,you could get a list of User Object form json format string.

  OkHttpProxy.get()
                .url(URL_USER)
                .tag(this)
                .enqueue(new OkCallback<List<User>>(new OkJsonParser<List<User>>() {
                }) {
                    @Override
                    public void onSuccess(int code, List<User> users) {
                        tv_response.setText(users.toString());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        tv_response.setText(e.getMessage());
                    }
                });

###Custom Parser

By extends for OkJsonParser, you could custom your parser as following .

public class JokeParser<T> extends OkJsonParser<T> {

    @Nullable
    @Override
    public T parse(Response response) throws IOException {
        String jsonStr = response.body().string();
        try {
            jsonStr = new JSONObject(jsonStr).getJSONArray("comments").toString();
            return mGson.fromJson(jsonStr, new TypeToken<ArrayList<Joke>>() {
            }.getType());
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Then you can use as above.

OkHttpProxy.get()
                .url(Joke.getRequestUrl(1))
                .tag(this).enqueue(new OkCallback<List<Joke>>(new JokeParser()) {
            @Override
            public void onSuccess(int code, List<Joke> jokes) {
                tv_response.setText(jokes.toString());
            }

            @Override
            public void onFailure(Throwable e) {
                tv_response.setText(e.getMessage());
            }
        });

###GET String

Get String by useing OkTextParser.

 OkHttpProxy.get()
                .url(URL_BAIDU)
                .tag(this)
                .enqueue(new OkCallback<String>(new OkTextParser()) {
                    @Override
                    public void onSuccess(int code, String s) {
                        tv_response.setText(s);
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        tv_response.setText(e.getMessage());
                    }
                });

###Post

Post is also very easy.

OkHttpProxy.post()
                .url(URL_USERS)
                .tag(this)
                .addParams("name", "zhaokaiqiang")
                .addHeader("header", "okhttp")
                .enqueue(new OkCallback<ArrayList<User>>(new OkJsonParser<ArrayList<User>>() {
                }) {
                    @Override
                    public void onSuccess(int code, ArrayList<User> users) {
                        tv_response.setText(users.toString());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        tv_response.setText(e.getMessage());
                    }
                });

###Upload

/**
     *  Validity period if Token is12 hours, if the Token Invalid,please create it by follow website
     * Token website = http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken
     * AK = IUy4JnOZHP6o-rx9QsGLf9jMTAKfRkL07gNssIDA
     * CK = DkfA7gPTNy1k4HWnQynra3qAZhrzp-wmSs15vub6
     * BUCKE_NAME = zhaokaiqiang
     */
    public void uploadFile(View view) {

        File file = new File(Environment.getExternalStorageDirectory(), "jiandan02.jpg");
        if (!file.exists()) {
            Toast.makeText(MainActivity.this, "File not exits!", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> param = new HashMap<>();
        param.put("token", TOKEN);
        Pair<String, File> pair = new Pair("file", file);

        OkHttpProxy
                .upload()
                .url(URL_UPLOAD)
                .file(pair)
                .setParams(param)
                .setWriteTimeOut(20)
                .start(new UploadListener() {
                    @Override
                    public void onSuccess(Response response) {
                        tv_response.setText("isSuccessful = " + response.isSuccessful() + "\n" + "code = " + response.code());
                    }

                    @Override
                    public void onFailure(Exception e) {
                        tv_response.setText(e.getMessage());
                    }

                    @Override
                    public void onUIProgress(Progress progress) {
                        int pro = (int) ((progress.getCurrentBytes() + 0.0) / progress.getTotalBytes() * 100);
                        if (pro > 0) {
                            pb.setProgress(pro);
                        }
                        KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes());
                    }
                });
    }

###Download

 String desFileDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        OkHttpProxy.download(URL_DOWMLOAD, new DownloadListener(desFileDir, "json.jar") {

            @Override
            public void onUIProgress(Progress progress) {
                // if the content length is unknow, the progress.getTotalBytes() = -1
                int pro = (int) (progress.getCurrentBytes() / progress.getTotalBytes() * 100);
                if (pro > 0) {
                    pb.setProgress(pro);
                }
                KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes());
            }

            @Override
            public void onSuccess(File file) {
                tv_response.setText(file.getAbsolutePath());
            }

            @Override
            public void onFailure(Exception e) {
                tv_response.setText(e.getMessage());
            }
        });

##JCenter

compile 'com.github.zhaokaiqiang.okhttpplus:library:1.0.0'

##Inspiration

##About me

##License

Copyright 2015, 2016 ZhaoKaiQiang

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.

More Repositories

1

KLog

这是一个Android专用的LogCat工具,主要功能为打印行号、函数调用、Json解析、XML解析、点击跳转、Log信息保存等功能
Java
1,904
star
2

AndroidDifficultAnalysis

安卓开发中遇到的重难点解析,也包括平常的读书笔记和知识点整理
1,172
star
3

JianDan

高仿煎蛋客户端
Java
762
star
4

ParticleLayout

左滑粒子效果
Java
405
star
5

JianDanRxJava

使用Rxjava重构煎蛋高仿
Java
240
star
6

PMNote

产品经理读书笔记
208
star
7

SelectCityModule

选择省份或者是城市模块,可以直接拿来用
Java
102
star
8

JianDan_OkHttpWithVolley

使用okhttp作为Volley底层请求框架的煎蛋高仿客户端
Java
75
star
9

RushBuyCountDownTimerView

RushBuyCountDownTimerView是一个自定义控件,模仿的是淘宝客户端Android版本,首页上面的抢购倒计时的效果。
Java
71
star
10

AppleWatchView

仿苹果手表Launcher
Java
55
star
11

AutoLoadListView

这是一个可以实现下拉刷新和自动加载下一页的ListView,下拉刷新使用Google的原生效果
Java
53
star
12

ZListVIew

整合了刷新、加载更多、滑动删除功能的ZListview
Java
50
star
13

SlideSelectView

这是一个滑动选择器,类似于SeekBar的效果
Java
48
star
14

ZhiHuDetailDemo

仿知乎回答详情界面
Java
44
star
15

MultiDexAsyncLoad

多Dex分包异步加载方案Demo
Java
42
star
16

FloatWindow

悬浮窗实现
Java
35
star
17

SwipeRefreshLoadListview

带有刷新、加载、滑动删除功能的Listview,现在已经废弃,请关注相同功能的项目,ZListVIew
Java
35
star
18

SinVoiceDemo

声波通信Demo
Java
34
star
19

car3d

3D汽车可旋转模型的实现
Java
32
star
20

MdImageResolver

解析Markdown本地图片文件,并自动完成图片文件的上传和内容的替换,图床为七牛云服务器
Java
28
star
21

AndroidDemo

凯子哥御用API测试Demo集合,大家一起学Android呀~
Java
27
star
22

TeachMask

APP教学蒙板实现
Java
24
star
23

JianDan_OkHttp

OkHttp网络请求实现的煎蛋
Java
20
star
24

InnerListview

可以镶嵌在Listview或者是ScrollView里面的ListView
Java
19
star
25

CountDownTimerDemo

倒计时的Button控件帮助类
Java
16
star
26

CropImageDemo

android裁剪实现dmeo
Java
12
star
27

JianDan_AsyncHttpClient

使用Android Asynchronous Http Client网络模块封装的煎蛋客户端
Java
12
star
28

AndroidArticle

12
star
29

ExceptionDemo

自定义的程序崩溃处理Demo
Java
9
star
30

IndicatorNavigationBar

带有指示器的底部导航栏
Java
9
star
31

EditTextShakeHelper

输入框震动效果帮助类
Java
9
star
32

LoadingDialog

动画加载框
Java
8
star
33

actionbartabs

原生控件实现侧滑栏和滑动Tab
Java
7
star
34

JsonDemo

各种方式解析Json字符串的示例
Java
6
star
35

MultyChoiceDemo

使用ActionMode实现的多选删除功能,有动画效果
Java
6
star
36

ScrollerDemo

是一个Scroller的演示demo
Java
5
star
37

CrashDemo

试一下,我能把你的手机搞崩不
Java
4
star
38

zhaokaiqiang.github.io

个人技术Blog
HTML
3
star
39

ScrollingTabsDemo

ScrollingTabsView的演示Demo
Java
2
star
40

RxAndroidDemo

这是RxAndroid的Demo,正在学习中,将持续更新,欢迎关注
Java
2
star
41

Article

2
star
42

AnimationWelcome

动态的APP欢迎界面
1
star