android

okhttp的封装

2019-05-15  本文已影响0人  leap_

params类

public class RequestParams {
    public ConcurrentHashMap<String,String> urlParams = new ConcurrentHashMap<>();
    public ConcurrentHashMap<String,Object> fileParams = new ConcurrentHashMap<>();


    public RequestParams(Map<String,String> souce){
        if (souce!=null){
            for (Map.Entry<String,String> entry : souce.entrySet()){
                put(entry.getKey(),entry.getValue());
            }
        }
    }

    public RequestParams(final String key , final String value) {
        this(new HashMap<String, String>(){
            {
                put(key, value);
            }
        });

    }

    public void put(String key , String value){
        if(key!=null && value!=null){
            urlParams.put(key, value);
        }
    }

    public void put(String key , Object value){
        if(key!=null && value!=null){
            fileParams.put(key, value);
        }
    }

    public boolean hasParams(){
        return urlParams.size() > 0 || fileParams.size() > 0;
    }

}

client对象

public class CommonOkHttpClient {

    private static OkHttpClient mClient;

    static {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.connectTimeout(30,TimeUnit.SECONDS);
        clientBuilder.readTimeout(30,TimeUnit.SECONDS);
        clientBuilder.writeTimeout(30,TimeUnit.SECONDS);
        // 允许重定向
        clientBuilder.followRedirects(true);

        // https支持
        clientBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        mClient = clientBuilder.build();
    }

    public static Call sendRequest(Request request, Callback callBack){
        Call call = mClient.newCall(request);
        call.enqueue(callBack);
        return call;
    }
}

request对象

public class CommonOkhttpRequest {

    public static Request createPostRequest(String url,RequestParams params){
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        // 添加参数
        if(params!=null){
            for (Map.Entry<String,String> entry:params.urlParams.entrySet()){
                bodyBuilder.add(entry.getKey(),entry.getValue());
            }
        }
        // 创建请求体
        FormBody formBody = bodyBuilder.build();
        // 创建request
        return new Request.Builder().post(formBody).url(url).build();
    }

    public static Request createGetRequest(String url,RequestParams params){
        // 如果params不为空,构建新的url
        if (params!=null){
            StringBuilder stringBuilder = new StringBuilder(url).append("?");
            for (Map.Entry<String,String> entry : params.urlParams.entrySet()){
                stringBuilder.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue())
                        .append("&");
            }
            // 去除最后的&
            url = stringBuilder.substring(0,stringBuilder.length()-1);
        }
        return new Request.Builder().url(url).get().build();
    }
}

callbackListener

public interface CallBackListener {
    void onSuccess(Response response);
    void onFailure(Exception e);
}

callback

public class CommonJSONCallBack implements Callback {

    Handler handler;
    CallBackListener listener;

    public CommonJSONCallBack(CallBackListener listener) {
        // 创建主线程的handler
        handler = new Handler(Looper.getMainLooper());

        this.listener = listener;
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.onFailure(e);
            }
        });
    }

    @Override
    public void onResponse(final Call call, final Response response) throws IOException {
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.onSuccess(response);
            }
        });

    }
}

上一篇 下一篇

猜你喜欢

热点阅读