9
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 的新手,谢谢——

4

3 回答 3

16

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

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

然后调用为:

getExampleMethod("Basic " + token, id);
于 2016-01-16T04:55:52.737 回答
9

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.

于 2016-04-06T06:19:41.120 回答
6

从改造:2.0

您必须使用OkHttpClient.Builder()类来添加Interceptors

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

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();
于 2016-04-06T08:51:11.297 回答