Retrofit 2.0 headers authentication

北慕城南 提交于 2019-12-04 21:40:32

问题


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);
}

This now gives me a failure return in Retrofit 2.0, originally I had it without the "Authorization" header and it was giving me unauthorized, which is understandable. But now I'm authorizing it with my auth token and it fails. New to Retrofit 2.0, thanks --


回答1:


You can pass Authorization Header as:

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

and then call as:

getExampleMethod("Basic " + token, id);



回答2:


You can add Authorization Header for every calls using Interceptor in Retrofit 2, by using the OkHttpClient.Builder class. Like this.

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();

And add this client object to the retrofit object.

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

Now for every calls that you make using the retrofit object will add the "Authorization" header along with the url. And also we handle the condition that if the authorization value is empty, then we simply omit the Authorization header part for the request call.




回答3:


From Retrofit:2.0

you have to use OkHttpClient.Builder() class to add Interceptors.

So you have to change your code like this.

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();


来源:https://stackoverflow.com/questions/34821958/retrofit-2-0-headers-authentication

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