package com.example.interceptordemo;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
//连接器使用的是责任链模式
public class NewIntercepter implements Interceptor {
private Response response;
@Override
public Response intercept(Chain chain) throws IOException {
//1、获取用户使用的请求方式
//1.1获取原始的请求
Request orginalRequest = chain.request();
//1.2获取请求方式
if ("GET".equals(orginalRequest.method())) {
//GET请求
//获取原始的请求地址,然后添加参数,生成最终的请求地址
HttpUrl url = orginalRequest.url()
.newBuilder()
.addQueryParameter("mobile", "18310830365")//添加参数
.addQueryParameter("password", "123456")
.build();
Request request = orginalRequest.newBuilder().url(url).build();
//发送拼接好参数的请求
response = chain.proceed(request);
} else if ("POST".equals(orginalRequest.method())) {
//POST请求
FormBody.Builder builder = new FormBody.Builder();
//获取原始的请求体里的参数
FormBody formBody = (FormBody) orginalRequest.body();
//遍历原始的请求体里的参数
for (int i = 0; i < formBody.size(); i++) {
builder.add(formBody.name(i), formBody.value(i));
}
//添加新参数
builder.add("mobile", "18310830365");
builder.add("password", "123456");
FormBody body = builder.build();
//添加请求的参数
Request request = orginalRequest.newBuilder()
.url(orginalRequest.url())
.post(body)
.build();
response = chain.proceed(request);
}
return response;
}
}
okhttp拦截器Interceptor
最新推荐文章于 2022-06-24 23:06:32 发布