How to add headers to OkHttp request interceptor?

前端 未结 10 1525
感情败类
感情败类 2020-12-01 00:24

I have this interceptor that i add to my OkHttp client:

public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Cha         


        
10条回答
  •  庸人自扰
    2020-12-01 00:58

    here is a useful gist from lfmingo

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
    httpClient.addInterceptor(new Interceptor() {
    
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
    
            Request request = original.newBuilder()
                .header("User-Agent", "Your-App-Name")
                .header("Accept", "application/vnd.yourapi.v1.full+json")
                .method(original.method(), original.body())
                .build();
    
            return chain.proceed(request);
        }
    }
    
    OkHttpClient client = httpClient.build();
    
    Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
    

提交回复
热议问题