我試圖用認證標頭髮送請求,但似乎服務器無法識別客戶端。 我用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) { } });
}
謝謝!
我已經添加了這個自定義標題 - 沒有幫助。 –