Boss拦截模版

来源:互联网 发布:surface windows rt 编辑:程序博客网 时间:2024/05/14 19:53

拦截器:

public class MyInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        Request newRequest = chain.request().newBuilder()
                .addHeader("source", "android")
                .url(request.url())
                .build();

        return chain.proceed(newRequest);
    }

}


Gson:

public class GsonUtils {
    private static Gson instance;

    private GsonUtils() {

    }

    public static Gson getInstance() {
        if (instance == null) {
            instance = new Gson();
        }

        return instance;
    }
}


OK:

public class OkHttpUtils {
    private static volatile OkHttpUtils instance;

    private OkHttpClient client;

    private Handler handler = new Handler();

    private OkHttpUtils() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new MyInterceptor())
                .build();
    }

    public static OkHttpUtils getInstance() {
        if (null == instance) {
            synchronized (OkHttpUtils.class) {
                if (instance == null) {
                    instance = new OkHttpUtils();
                }
            }
        }
        return instance;
    }

    public void post(String url, Map<String, Object> map, final CallBack callBack, final Class cls) {
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                builder.add(entry.getKey(), (String) entry.getValue());
            }
        }

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

        Call call = client.newCall(request);

神略......

}

原创粉丝点击