如何为所有请求设置标头?

时间:2018-02-26 20:28:14

标签: android retrofit2

在我的应用程序中,我使用Retrofit来获取来自服务器的请求 我希望将标题设置为所有请求,我在下面编写代码:

public class ApiClient {
    private static final String BASE_URL = "http://example.com/api/v1.0.0.1/Api/";
    private static Retrofit retrofit = null;

    public static Gson gson = new GsonBuilder().create();

    public static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.interceptors().add(interceptor);
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("Device", "2").build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = builder
                .connectTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(client)
                    .build();
        }
        return retrofit;
    }
}

但是在运行应用程序时,不要设置此标题!

我该怎么办?请帮帮我

0 个答案:

没有答案