OkHttp3实现简单封装Get/Post/拦截器

依赖:

implementation 'com.squareup.okhttp3:okhttp:3.9.+'

或者去获取最新OkHttp版本

应用拦截器

/**
 * 自定义一个拦截器,每次请求之前携带公共参数
 *
 * 应用层
 *
 */

public class CommonParamsInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        //得到原始的请求对象
        Request request = chain.request();
        //得到用户所使用的请求方式
        String method = request.method();

        if("GET".equals(method)){
            //url
            //原始的请求接口
            String oldUrl = request.url().toString();

            //拼接成一个新的URL
            String newUrl = oldUrl + "&source=android";

            //重新构建请求体
            request = new Request.Builder()
                    .url(newUrl)
                    .build();
        }else if("POST".equals(method)){
            //得到原始的url
            String oldUrl = request.url().toString();
            //得到原有的请求参数
            FormBody oldBody = (FormBody) request.body();//1 2 3

            //新的构建项
            FormBody.Builder builder = new FormBody.Builder();
            for (int i =0 ; i < oldBody.size(); ++i){
                //取出相关请求参数(原有的)
                String name = oldBody.name(i);
                String value = oldBody.value(i);
                //将原始的参数拼装到新的构建体当中
                builder.add(name,value);
            }

            //拼装我们的公共参数
            builder.add("source","android");

            request = new Request.Builder()
                    .url(oldUrl)
                    .post(builder.build())
                    .build();


        }
        //重新发送请求
        return chain.proceed(request);
    }
}

定义一个接口类

public interface OnFinishListener {


    void onFailed(String msg);

    void onSuccess(Object obj);


}

代码块

单例模式SingTask

private static OkHttpUtils OK_HTTP_UTILS = null;
//定义一个Handler
private static Handler handler = new Handler();

private OkHttpUtils() {
}


/**
 * 得到OkHttpUtils实例对象
 *
 * @return
 */
public static OkHttpUtils getInstance() {

    if (null == OK_HTTP_UTILS) {

        synchronized (OkHttpUtils.class) {

            if (null == OK_HTTP_UTILS) {
                OK_HTTP_UTILS = new OkHttpUtils();
            }
        }

    }
    return OK_HTTP_UTILS;

}

GET请求

/**
 * Get请求
 *
 * @param path http://www.baidu.com?key=value&key=value
 * @param onFinishListener
 */
public void doGet(String path,Map map,final OnFinishListener onFinishListener) {

    //Http:/www.baidu.com?key=ddd&
    StringBuffer sb = new StringBuffer();
    sb.append(path);
    //判断path是否包含一个
    if(sb.indexOf("?") != -1){

        //判断"?"是否在最后一个
        if(sb.indexOf("?") != sb.length() -1){
            sb.append("&");
        }

    }else{
        sb.append("?");
    }

    //遍历map集合中所有请求参数
    for (Map.Entry entry: map.entrySet()){
        sb.append(entry.getKey())
                .append("=")
                .append(entry.getValue())
                .append("&");
    }

    //判断get请求路径最后是否包含一个"&"
    if(sb.lastIndexOf("&") != -1){
        sb.deleteCharAt(sb.length() - 1);
    }


    OkHttpClient okHttpClient = new OkHttpClient.Builder()

            //添加应用拦截器
            .addInterceptor(new CommonParamsInterceptor())
            //.addNetworkInterceptor() //添加网络拦截器
            .build();

    //构建请求项
    Request request = new Request.Builder()
            .get()
            .url(sb.toString())
            .build();

    Call call = okHttpClient.newCall(request);
    //execute 子线程  enqueue //
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            //请求失败

            handler.post(new Runnable() {
                @Override
                public void run() {
                    onFinishListener.onFailed(e.getMessage());
                }
            });


        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            //得到服务器的响应结果
            final String result = response.body().string();

            //请求成功
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //主线程当中执行
                    onFinishListener.onSuccess(result);
                }
            });
        }
    });

}

POST请求

public void doPost(String path, Map map, final OnFinishListener onFinishListener) {


    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //添加应用拦截器 公共参数
            .addInterceptor(new CommonParamsInterceptor())
            .build();

    //构建参数的对象
    FormBody.Builder builder = new FormBody.Builder();

    //遍历map集合,获取用户的key/value
    for (String key : map.keySet()) {
        builder.add(key, map.get(key));
    }

    /*FormBody body = new FormBody.Builder()
            .add("mobile",mobile)
            .add("password",password)
            .build();*/
    //构建请求项
    final Request request = new Request.Builder()
            .post(builder.build())
            .url(path)
            .build();
    Call call = okHttpClient.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onFinishListener.onFailed(e.getMessage());
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            final String result = response.body().string();//这句话必须放到子线程里


            System.out.println("OkHttUitls 线程名 : " + Thread.currentThread().getName());

            handler.post(new Runnable() {
                @Override
                public void run() {
                    onFinishListener.onSuccess(result);
                }
            });

        }
    });
}

你可能感兴趣的:(Android入门学习)