自定义拦截器

时间:2021-06-01 10:21:05

MyInterceptor post

public class MyInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//获取原始的请求数据
Request orginRequest = chain.request();
//先获取原始的请求参数,然后再拼接起来
FormBody orginBody = (FormBody) orginRequest.body();
FormBody.Builder builder = new FormBody.Builder();
for (int i = 0; i < orginBody.size(); i++) {
String name = orginBody.name(i);
String value = orginBody.value(i);
builder.add(name, value);
}
builder.add("source", "android");
FormBody formBody = builder.build();
Request request = new Request.Builder().url(orginRequest.url()).post(formBody).build();

return chain.proceed(request);

}
}

 get自定义拦截器

public class MyInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url();
String string = url.url().toString();
String resultUrl = string+"&source=android";

Request request1 = request.newBuilder().url(resultUrl).build();

return chain.proceed(request);
}
}

网络请求类

public class HttpUtils {
private static HttpUtils httpUtils;
private final OkHttpClient client;

private HttpUtils() {
//创建OkHttpClient
//创建拦截器

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

public static HttpUtils getHttpUtils() {
if (httpUtils == null) {
synchronized (HttpUtils.class) {
if (httpUtils == null) {
httpUtils = new HttpUtils();
}
}
}
return httpUtils;
}

/**
* GET请求
*
* @param url 请求地址
* @param callback 回调
*/
public void doGet(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}

/**
* POST请求
*
* @param url 请求地址
* @param params 请求的参数
* @param callback 回调
*/
public void doPost(String url, Map<String, String> params, Callback callback) {
//这里可以加网络判断

//判断参数
if (params == null || params.size() == 0) {
throw new RuntimeException("params is null!!!");
}
// 创建Request
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
FormBody formBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
client.newCall(request).enqueue(callback);
}
}