okHttp+拦截器 拦截器用来放置公共参数

compile ‘com.squareup.okhttp3:okhttp:3.4.1’

———-OKhttp封装类 拦截器已注释
package com.example.jingdong.OkHttp;

import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
* Created by Administrator on 2017/12/13 0013.
*/

public class OkHttpUtils {

private static OkHttpUtils okHttpUtils = null;
private static Handler handler = new Handler();

private OkHttpUtils(){}
/**
 * 获取当前这个类的实例
 * @return
 */
public static OkHttpUtils getInstance(){
    if(null == okHttpUtils){
        synchronized (OkHttpUtils.class){
            if(null == okHttpUtils){
                okHttpUtils = new OkHttpUtils();
            }
        }
    }
    return okHttpUtils;
}
/**
 * get请求
 * @param path
 * @param map
 */
public void doGet(String path, Map<String,String> map, final OnFinishListener onFinishListener){



    StringBuilder sb = null;

    for (String key : map.keySet()) {

        //login?name=124e3434&p=ere

        if(null == sb){
            sb = new StringBuilder();
            sb.append("?");
        }else{

            sb.append("&");

        }

        //拼接参数
        sb.append(key).append("=").append(map.get(key));
    }


    OkHttpClient okHttpClient = new OkHttpClient();

/* //应用拦截器
OkHttpClient okHttpClient1=new OkHttpClient.Builder()
.addInterceptor(new CommonParamsinterceptor())
.build();*/

    final Request request = new Request.Builder()
            .url(path+sb.toString())
            .get()
            .build();
    Log.d("gggg",path+sb.toString());

    okhttp3.Call call = okHttpClient/*使用拦截器此处需要换上拦截器名*/.newCall(request);
    call.enqueue(new Callback() {

        public void onFailure(okhttp3.Call call, final IOException e) {

            //在子线程
            handler.post(new Runnable() {
                @Override
                public void run() {

                    onFinishListener.onFailed(e.getMessage());

                }
            });
        }

        public void onResponse(okhttp3.Call call, final Response response) throws IOException {


            final String result = response.body().string();


            handler.post(new Runnable() {
                @Override
                public void run() {

                    try {

                        onFinishListener.onSuccess(result);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

        }
    });

}

}

———- 用来返回请求结果的接口
package com.example.jingdong.OkHttp;

/**
* Created by Administrator on 2017/12/13 0013.
*/

public interface OnFinishListener {

void onSuccess(String result);
void onFailed(String msg);

}

———- 拦截器类
package com.example.jingdong.OkHttp;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
* Created by Administrator on 2017/12/13 0013.
*/

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();

        //拼接公共参数
        String newurl=oldurl+"&source=android";

        //构建新的request
        request=new Request.Builder()
                .url(newurl)
                .build();



    }else if("POST".equals(method)){
        //取出旧的参数和URL
        FormBody body=(FormBody)request.body();

        String oldUrl=request.url().toString();

       //构建新的FromBody
        FormBody.Builder newFormBody = new FormBody.Builder();

        for (int i = 0; i < body.size();i++){

            String key = body.name(i);//keywors
            String value = body.value(i);//value

            newFormBody.add(key,value);
        }
        //公共参数
        newFormBody.add("source","android");

        //新构建的reqeust
        request = new Request.Builder()
                .url(oldUrl)
                .post(newFormBody.build())
                .build();
    }
    return chain.proceed(request);
}

}

///使用方法

     OkHttpUtils ok=OkHttpUtils.getInstance();

    Map<String,String> map=new HashMap<>();
    map.put("","");

    //请求轮播图
    ok.doGet("http://120.27.23.105/ad/getAd", map,new OnFinishListener() {
        @Override
        public void onSuccess(String result) {

            Gson gson=new Gson();

            ShouYeBunnerBean sbb=gson.fromJson(result,ShouYeBunnerBean.class);


            neibu.lunbo(sbb);
        }
        @Override
        public void onFailed(String msg) {
        }
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值