【问题标题】:Add headers to request using Retrofit 2使用 Retrofit 2 向请求添加标头
【发布时间】:2018-03-29 04:48:05
【问题描述】:

我正在尝试发送带有身份验证标头的请求,但似乎服务器无法识别客户端。 我用this教程,实现了一个拦截器,如下:

public class AuthenticationInterceptor implements Interceptor {

private String authId;
private String authToken;

public AuthenticationInterceptor(String authId, String authToken) {
    this.authId = authId;
    this.authToken = authToken;
}

@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder builder = original.newBuilder();

    if (authId != null && authToken != null) {
        Timber.d("adding auth headers for: " + this);
        builder.header("auth_id", authId)
                .header("auth_token", authToken);
    }

    Request request = builder.build();
    return chain.proceed(request);
  }
}

当我尝试向服务器发送经过身份验证的请求时,它返回错误响应 409。服务器人员告诉我,我缺少这些参数:(例如,由 Postman 接收)

    “accept”: [
        “*/*”
    ],
    “accept-encoding”: [
        “gzip, deflate”
    ],
    “cookie”: [
        “PHPSESSID=ah1i1856bkdln5pgmsgjsjtar3"
    ]
  • 我认为使用 Dagger2 可能会导致此问题(请参阅here),因此我已经隔离了 okHttpClient,但它仍然无法正常工作。

  • 这是我的使用实现(非常简单):

    Retrofit retrofit;
    OkHttpClient client;
    AuthenticationInterceptor authenticationInterceptor;
    HttpLoggingInterceptor loggingInterceptor;
    
    private void testHeaders() {
    loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Timber.i(message);
        }
    });
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    
    client = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build();
    
    retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .baseUrl(BuildConfig.SERVER_ADDRESS)
            .build();
    
    retrofit.create(EntrOnline.class).getLoginToken("email@email.com", "XXX").enqueue(new Callback<NewAccount>() {
        @Override
        public void onResponse(Call<NewAccount> call, Response<NewAccount> response) {
    
            authenticationInterceptor = new AuthenticationInterceptor(response.body().getAuthId(), response.body().getAuthToken());
    
            client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(authenticationInterceptor)
                    .build();
    
            retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .baseUrl(BuildConfig.SERVER_ADDRESS)
                    .build();
    
            retrofit.create(EntrOnline.class).getKeys("50022d8a-b309-11e7-a902-0ac451eb0490").enqueue(new Callback<List<NewEkey>>() {
                @Override
                public void onResponse(Call<List<NewEkey>> call, Response<List<NewEkey>> response) {
                    Timber.d("Test Api");
                }
    
                @Override
                public void onFailure(Call<List<NewEkey>> call, Throwable t) {
    
                }
            });
    
        }
    
        @Override
        public void onFailure(Call<NewAccount> call, Throwable t) {
    
        }
    });
    

    }

谢谢!

【问题讨论】:

    标签: android retrofit session-cookies interceptor okhttp3


    【解决方案1】:

    看起来像server issue。 您可以尝试在拦截器中添加他谈到的标头。

    builder.addHeader("Accept", "*/*").addHeader("accept-encoding",  "gzip, deflate")
    

    但是应该在网络上使用 cookie 来跟踪当前会话。 API 上不需要。

    【讨论】:

      【解决方案2】:
      @Headers("Accept: application/json")
      @FormUrlEncoded
      @POST("sendWalletMoney")
      Call<WalletResponse> sendWalletMoney(@Field("sender") String sender,
                                           @Field("receiver") String receiver,
                                           @Field("amount") String amount,
                                           @Field("trnsx_type") String trnsx_type,
                                           @Field("currency") String currency,
                                           @Field("module_name") String module_name);
      

      【讨论】:

      • 我已经添加了这个自定义标题 - 没有帮助。
      猜你喜欢
      • 2015-12-12
      • 1970-01-01
      • 2015-03-22
      • 2021-08-13
      • 1970-01-01
      • 2012-01-30
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多