Retrofit 2.0标头身份验证 [英] Retrofit 2.0 headers authentication

查看:108
本文介绍了Retrofit 2.0标头身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中失败返回,原来我没有"Authorization"标头,却给了我未授权的情况,这是可以理解的.但是现在我用我的auth令牌授权了它,但是它失败了. Retrofit 2.0的新功能,谢谢-

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 --

推荐答案

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

You can pass Authorization Header as:

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

然后调用为:

getExampleMethod("Basic " + token, id);

这篇关于Retrofit 2.0标头身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆