当前位置: 移动技术网 > 移动技术>移动开发>Android > 【Android】OkHttp3总结与封装

【Android】OkHttp3总结与封装

2019年03月18日  | 移动技术网移动技术  | 我要评论

开始使用

在app目录下的build.gradle中添加依赖:

implementation 'com.squareup.okhttp3:okhttp:3.13.1'
implementation 'com.squareup.okio:okio:2.2.2'

get方法

okhttpclient client = new okhttpclient.builder().build();
request.builder builder = new request.builder().url(url);
builder.method("get", null);
request request = builder.build();
call call = client.newcall(request);
call.enqueue(new callback() {
    @override
    public void onfailure(call call, ioexception e) {
        ...
    }

    @override
    public void onresponse(call call, response response) throws ioexception {
        ...
    }
});

get参数的传递可以使用拼接字符串的方式直接拼接到url中。

post方法

okhttpclient client = new okhttpclient.builder().build();
formbody.builder formbody = new formbody.builder();
formbody.add(key,value);
... // 添加参数
requestbody form = formbody.build();
request.builder builder = new request.builder();
request request = builder.post(form)
        .url(url)
        .build();
call call = client.newcall(request);
call.enqueue(new callback() {
    @override
    public void onfailure(call call, ioexception e) {
        ...
    }

    @override
    public void onresponse(call call, response response) throws ioexception {
        ...
    }
});

封装

由于okhttp发送请求的方式比较繁琐,需要构建许多参数,所以需要我们自己进行封装,以下是我的封装方式:

/**
- @author:y4ngyy
*/

public class httpclient {
    private okhttpclient client;
    private static httpclient mclient;
    private context context;
    private httpclient(context c) {
        context = c;
        client = new okhttpclient.builder()
                .cookiejar(new persistentcookiejar(new setcookiecache(), new sharedprefscookiepersistor(context)))
                .followredirects(true)
                .followsslredirects(true)
                .build();
    }

    public static httpclient getinstance(context c){
        if (mclient == null) {
            mclient = new httpclient(c);
        }
        return  mclient;
    }


    // get方法
    public void get(string url, hashmap<string,string> param, mycallback callback) {
        // 拼接请求参数
        if (!param.isempty()) {
            stringbuffer buffer = new stringbuffer(url);
            buffer.append('?');
            for (map.entry<string,string> entry: param.entryset()) {
                buffer.append(entry.getkey());
                buffer.append('=');
                buffer.append(entry.getvalue());
                buffer.append('&');
            }
            buffer.deletecharat(buffer.length()-1);
            url = buffer.tostring();
        }
        request.builder builder = new request.builder().url(url);
        builder.method("get", null);
        request request = builder.build();
        call call = client.newcall(request);
        call.enqueue(new callback() {
            @override
            public void onfailure(call call, ioexception e) {
                callback.failed(e);
            }

            @override
            public void onresponse(call call, response response) throws ioexception {
                callback.success(response);
            }
        });
    }

    public void get(string url, mycallback callback) {
        get(url, new hashmap<string, string>(), callback);
    }

    // post 方法
    public void post(string url, hashmap<string, string> param, mycallback callback) {
        formbody.builder formbody = new formbody.builder();
        if(!param.isempty()) {
            for (map.entry<string,string> entry: param.entryset()) {
                formbody.add(entry.getkey(),entry.getvalue());
            }
        }
        requestbody form = formbody.build();
        request.builder builder = new request.builder();
        request request = builder.post(form)
                .url(url)
                .build();
        call call = client.newcall(request);
        call.enqueue(new callback() {
            @override
            public void onfailure(call call, ioexception e) {
                callback.failed(e);
            }

            @override
            public void onresponse(call call, response response) throws ioexception {
                callback.success(response);
            }
        });
    }
    public interface mycallback {
        void success(response res) throws ioexception;
        void failed(ioexception e);
    }
}

想法有以下几点:

  1. get()post()方法中,将需要的参数以hashmap传递键值对,并把相应操作封装。
  2. 第二个get()重载是考虑到不需要参数的get请求的情况。
  3. 留下mycallback接口来对不同请求做处理。
  4. 由于需要保持cookie来做登录等操作,所以用到了第三方库persistentcookiejar
  5. 考虑到cookie的问题,在不同的activity间需要使用同一个实例才行,有想过使用intent序列化传递对象,但由于activity太多,传递太繁琐,所以直接写成单例模式。

对于okhttp的源码还没有深究,有时间再继续研究。

只是菜鸡一个..有错还请指正..继续努力学习

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网