改进2.0标头身份验证

时间:2016-01-16 00:05:58

标签: http-headers interceptor retrofit2

private void setUpRestClient() {
       OkHttpClient client = new OkHttpClient();
       client.interceptors().add(new Interceptor() {
           @Override
           public Response intercept(Chain chain) throws IOException {
               Request original = chain.request();
               Request request = original.newBuilder()
                       .header("Accept", "application/pyur.v1")
                       .header("Authorization", new SharedPreferencesUtil(getBaseContext()).getToken())
                       .header("Content-Type", "application/json")
                       .method(original.method(),original.body())
                       .build();
               return chain.proceed(request);
           }
       });
       RestClient.getInstance().configureRestAdapter(this, getResources().getString(R.string.base_url),client);
   }

public void configureRestAdapter(final Context context, String baseUrl, OkHttpClient client) {
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build();
    service = retrofit.create(NetworkServiceInterface.class);
}

现在这让我在Retrofit 2.0中失败了,原来我没有“授权”标题而且没有授权给我,这是可以理解的。但是现在我用我的身份验证令授权它并且它失败了。 Retrofit 2.0的新功能,谢谢 -

3 个答案:

答案 0 :(得分:13)

您可以将授权标题传递为:

@GET("/v1/OrderReport.json")
Call<POJO_Class> getExampleMethod(@Header("Authorization") String token, @Query("id") String id);

然后调用:

getExampleMethod("Basic " + token, id);

答案 1 :(得分:7)

您可以使用OkHttpClient.Builder类在Retrofit 2中使用Interceptor为每次调用添加Authorization Header。像这样。

import okhttp3.OkHttpClient;
import okhttp3.Interceptor;

OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {
                            //getAccessToken is your own accessToken(retrieve it by saving in shared preference or any other option )
                                if(getAccessToken().isEmpty()){ 
                                    PrintLog.error("retrofit 2","Authorization header is already present or token is empty....");
                                    return chain.proceed(chain.request());
                                }
                                Request authorisedRequest = chain.request().newBuilder()
                                        .addHeader("Authorization", getAccessToken()).build();
                                PrintLog.error("retrofit 2","Authorization header is added to the url....");
                                return chain.proceed(authorisedRequest);
                            }}).build();

将此客户端对象添加到改装对象。

retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) //BaseURL always ends with "/"
                .addConverterFactory(GsonConverterFactory.create())
                .client(defaultHttpClient)
                .build();

现在,您使用改装对象进行的每次调用都会添加&#34;授权&#34;标题以及网址。此外,我们还处理了如果授权值为空,那么我们只需省略请求调用的Authorization标头部分。

答案 2 :(得分:4)

来自改造:2.0

您必须使用 OkHttpClient.Builder()类添加拦截器

所以你必须像这样改变你的代码。

OkHttpClient client = new OkHttpClient.Builder();
       client.addInterceptor(new Interceptor() {
           @Override
           public Response intercept(Chain chain) throws IOException {
               Request original = chain.request();
               Request request = original.newBuilder()
                       .header("Accept", "application/pyur.v1")
                       .header("Authorization", new SharedPreferencesUtil(getBaseContext()).getToken())
                       .header("Content-Type", "application/json")
                       .method(original.method(),original.body())
                       .build();
               return chain.proceed(request);
           }
       }).build();