我试图用认证标头发送请求,但似乎服务器无法识别客户端。 我用this教程,并实施拦截如下:使用Retrofit添加标头2
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的服务器家伙告诉我,我缺少这些PARAMS:(其收到邮差例如)
“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 protected]", "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) { } });
}
谢谢!
我已经添加了这个自定义标题 - 没有帮助。 –