java 改造添加带有令牌和 ID 的标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/41514375/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrofit add header with token and id
提问by Ruslan Myhal
I have a problem with getting authenticated user. Before it I got token and user id. Now i need to get user from server using access token and id. I have header format
我在获取经过身份验证的用户时遇到问题。在此之前,我获得了令牌和用户 ID。现在我需要使用访问令牌和 ID 从服务器获取用户。 我有标题格式
Now I'am trying to add header with user token and id using interceptor.
现在我正在尝试使用拦截器添加带有用户令牌和 id 的标头。
My code:
我的代码:
Interceptor interceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request newRequest = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("authorization", token) <-??
                    .addHeader("driver_id", id) <-??
                    .build();
            return chain.proceed(newRequest);
        }
    };
    OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.addInterceptor(interceptor);
    OkHttpClient okHttpClient = okHttpBuilder.build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();
Interface:
界面:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver();
Different variants throws 401 error, don't know what to do Log:
不同的变种抛出401错误,不知道怎么办日志:
I/Response?code: 401
I/Response?message: Unauthorized`
回答by Ruslan Myhal
I got it. It's must look like:
我知道了。它必须看起来像:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String auth);
And auth:
和授权:
Call<Driver> call = apiInterface.getAuthorizedDriver("Token token=" + token + ", driver_id=" + id);
回答by Malik
Try to pass the header values via the method call:
尝试通过方法调用传递标头值:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String token,
                                 @Header("driver_id") Integer id);
You also wouldn't have to deal with this huge chunk of Interceptor code
您也不必处理这么大的拦截器代码

![java 无法启动组件 [StandardEngine[Catalina].StandardHost[localhost]](/res/img/loading.gif)