1. 程式人生 > >okhttp攔截器新增請求頭

okhttp攔截器新增請求頭

新建一個類UserAgentInterceptor實現Interceptor

import java.io.IOException;

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

/**
 * 新增請求頭
 */
public class UserAgentIntercepter implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request =  chain.request().newBuilder()
                .addHeader("key1","value")
                .build();

        return chain.proceed(request);
    }
}

在okhttputils封裝類裡新增 攔截器
 .addInterceptor(new UserAgentIntercepter())