utils包 OkHttp封装 + OkHttp拦截器

全部是utils包下的


一,  CommonParamsInterceptor  类

/**
 * 自定义一个拦截器,每次请求之前携带公共参数
 */
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);
    }
}
 
OkHttpUtils 类

/**
 * OkHttp  封装
 */
public class OkHttpUtils {
    private static OkHttpUtils OK_HTTP_UTILS = null;
    //定义一个Handler
    private static Handler handler = new Handler();
    private OkHttpUtils() {
    }
    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请求
     */
    public void doGet(String path,Map<String,String> 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<String, String> 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<String, String> 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));
        }
        //构建请求项
        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);
                    }
                });
            }
        });
    }
    /**
     * 上传文件
     * @param path 上传文件路径
     * @param params  上传的参数
     * @param onFinishListener 监听
     */
    public void upLoadFile(String path, Map<String,Object> params, final OnFinishListener onFinishListener){
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //设设置类型 以表单的形式提交
        builder.setType(MultipartBody.FORM);
        for (Map.Entry<String, Object> entry: params.entrySet()){
            Object object = entry.getValue();
            if(!(object instanceof File)){
                builder.addFormDataPart(entry.getKey(),object.toString());
            }else{
                File file = (File) object;
                builder.addFormDataPart(entry.getKey(),file.getName().trim(),
                        RequestBody.create(MediaType.parse("img/png"),file));
                //img/png -> application/octet-stream
            }
        }
        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, final Response response) throws IOException {
                //判断服务器是否响应成功
                if(response.isSuccessful()){
                    final String result = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            onFinishListener.onSuccess(result);
                        }
                    });
                }else{
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //服务器响应失败
                            onFinishListener.onFailed(response.message());
                        }
                    });
                }
            }
        });
    }
}
 
Constants  类

/**
 * 常量类
 */
public class Constants {
    //请求的服务器主机名
    public static final String HOST_NAME = "https://www.zhaoapi.cn";
    /**
     * 获取购物车信息
     */
    public static final String GET_CARTS = HOST_NAME+"/product/getCarts";
}
OnFinishListener  接口

public interface OnFinishListener {
    void onFailed(String msg);
    void onSuccess(Object obj);
}
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值