1、Interceptor
interface Interceptor {
@Throws(IOException::class)
fun intercept(chain: Chain): Response
interface Chain {
fun request(): Request
@Throws(IOException::class)
fun proceed(request: Request): Response
fun connection(): Connection?
fun call(): Call
fun connectTimeoutMillis(): Int
fun withConnectTimeout(timeout: Int, unit: TimeUnit): Chain
fun readTimeoutMillis(): Int
fun withReadTimeout(timeout: Int, unit: TimeUnit): Chain
fun writeTimeoutMillis(): Int
fun withWriteTimeout(timeout: Int, unit: TimeUnit): Chain
}
}
2、请求数据处理(只做基本功能说明)
- 修改参数(Content-Type:application/json)
private static final Interceptor requestInterceptor = chain -> {
Request request = chain.request();
//1、修改POST请求参数,可用于添加默认参数
if (request.method().equals("POST")) {
RequestBody body = request.body();
if (body instanceof FormBody) {
FormBody.Builder bodyBuilder = new FormBody.Builder();
//保存原始请求参数
for (int i = 0; i < ((FormBody) body).size(); i++) {
bodyBuilder.addEncoded(((FormBody) body).encodedName(i), ((FormBody) body).encodedValue(i));
}