android retrofit add custom header

做~自己de王妃 提交于 2019-12-13 03:40:14

问题


i using retrofit2 and want add some header using OkHttp3 addInterceptor but not working

this is my code

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .removeHeader("Authorization")
                    .removeHeader("Content-type")
                    .removeHeader("User-Agent")
                    .addHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("Accept-Language", "en-US")
                    .addHeader("User-Agent", ApiConfig.userAgent)
                    .method(original.method(), original.body())
                    .build();
            return chain.proceed(request);
        }
    });
OkHttpClient client = httpClient.build();

    if (apiInterface == null) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConfig.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        apiInterface = retrofit.create(ApiInterface.class);
    }
    return apiInterface;

please help me. kind regards


回答1:


Try this if it helps

RestAdapter.Builder builder = new RestAdapter.Builder()
    .setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Accept", "application/json;versions=1");
            if (isUserLoggedIn()) {
                request.addHeader("Authorization", getToken());
            }                    
        }
    });


来源:https://stackoverflow.com/questions/44235853/android-retrofit-add-custom-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!