网络请求库-Okhttp3

作者: CokeNello | 来源:发表于2016-12-03 15:39 被阅读268次

    0.参考:

    官网:

    文档:

    1 .导入

    • 依赖导入,请看官网上的依赖地址。
    • jar包导入,官网上有链接下载。

    2 .概念

    在Ok http中,有几个类我们需要理解一下:

    • OkHttpClient:客户端,理解为就是由它发起请求的
    • Request:请求,这个类负责组装起请求的一些基本参数:url,get/post,等等。
    • FormBody:请求的Body,在Post请求中,它就负责把请求的Parameter组装起来。
    • MultipartBody:Body,说明其也是包装Body体的,对比FormBody,FormBody只能组合String的key-value,而其可以组合其他类型的数据,可以设置MediaType等等。

    3 .基本用法

    1) 基本的GET请求
    同步调回,阻塞当前线程:

                OkHttpClient client = new OkHttpClient();               //新建客户端
                Request request = new Request.Builder()                 //新建请求
                        .get()                                                  //get请求
                        .url("http://publicobject.com/helloworld.txt")          //URL
                        .build();
                Response response = client.newCall(request).execute();          //返回对象
                if (response.isSuccessful()) {                                  //阻塞线程。
                    Log.e("code",":"+response.code());
                    Log.e("body",response.body().string());
                }
                else {
                    Log.e("---","不成功");
                }
    

    异步回调请求结果:

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .get()
                        .url("http://publicobject.com/helloworld.txt")
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("onFailure",e.getMessage());
                    }
    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.e("body",response.body().string());
                    }
                });
    

    2) 基本的POST请求
    POST 提交参数:异步回调,同步的写法如上面。

                OkHttpClient okHttpClient = new OkHttpClient();
    
                FormBody formBody = new FormBody.Builder()
                        .add("1","hehe")
                        .add("2","xixi")
                        .build();
    
                Request request = new Request.Builder()
                        .url("http://www.chestnutplus.com/Test/hello.php")
                        .post(formBody)
                        .build();
    
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("onFailure",e.getMessage());
                    }
    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.e("onResponse",response.body().string());
                    }
                });
    

    4 .高级一点的用法:

    高级?哈哈,先结合Rx吧。虽然Okhttp自身没有结合Rx,但是,我觉得这样还更好呢,因为,我们可以自己来DIY。

    RxGet

    public Observable<String> RxGet(String url, Map<String, String> map) {
                return Observable.create(subscriber -> {
                Request request = new Request.Builder()
                        .get()
                        .url(HttpUtils.assemblyGetParam(url,map))
                        .build();
                Call call = mOkHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        subscriber.onError(new Throwable("fail,msg:"+(e!=null?e.getMessage():"null")));
                    }
    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        subscriber.onNext(response.body().string());
                    }
                });
            });
        }
    

    RxPost

    public void Post(String url, Map<String, String> map, HttpCallBack callBack) {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : map.keySet()) {
                builder.add(key,map.get(key));
            }
            Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (callBack!=null)
                        callBack.onFailure("fail,msg:"+(e!=null?e.getMessage():"null"));
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (callBack!=null)
                        callBack.onSuccess(response.body().string());
                }
            });
    }
    

    5 .来传一下文件吧!

    文件的上传,这里只是一个简单的小文件,就是很小的文件,几百K吧。
    要使用Post上传。
    这里演示了上传一个MP3文件。

    public void PostFile(String url, Map<String,String> map, String fileName, byte[] fileBytes, HttpCallBack callBack) {
    
            MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM);
            RequestBody requestBody = RequestBody.create(MediaType.parse("audio/mp3"),fileBytes);
            body.addFormDataPart(fileName,"fileName"+".mp3",requestBody);
            for (String key : map.keySet()) {
                body.addFormDataPart(key,map.get(key));
            }
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(body.build())
                    .build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (callBack!=null)
                        callBack.onFailure("fail,msg:"+(e!=null?e.getMessage():"null"));
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (callBack!=null)
                        callBack.onSuccess(response.body().string());
                }
            });
        }
    

    6 .最后。

    我觉得呢,Okhttp还是挺好用的,对于我这种Java流派,Okhttp还能在Java平台上跑呢,
    像是Volley,只能用于Android上,伤心。
    小弟不才,希望各位不要扔鞋,提意见就好。

    相关文章

      网友评论

        本文标题:网络请求库-Okhttp3

        本文链接:https://www.haomeiwen.com/subject/zrjcmttx.html