接口:
@GET("burrowedbooks/")
Call<JsonArray> getCategoryList(@Header("Authorization") String token);
用法:
private LibraryAPi service;
Retrofit retrofit = new Retrofit.Builder()
//.client(client)
.baseUrl(String.valueOf(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(LibraryAPi.class);
// Extract token from Shared Preferences.
SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.login_data), MODE_PRIVATE);
String token = "Bearer "+prefs.getString("token","");
Call<JsonArray> categoryListResponseCall = service.getCategoryList(token);
categoryListResponseCall.enqueue(new Callback<JsonArray>() {
@Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
int statusCode = response.code();
Toast.makeText(getContext(), ""+statusCode, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<JsonArray> call, Throwable t) {
}
});
我正在尝试发送存储在共享首选项中的身份验证令牌。上面的代码不起作用。它返回403禁止状态代码。发送身份验证标头的正确方法是什么?
答案 0 :(得分:1)
.baseUrl(String.valueOf(R.string.base_url))
您应该使用.baseUrl(getActivity().getString(R.string.base_url))
但是您的代码不会向服务器发送数据,并且会调用onFailure
。
如果你正确地得到字符串并且仍然得到403,你可能想要使用邮递员验证你的后端实现。
答案 1 :(得分:0)
您还可以创建自定义拦截器,以便在新请求时自动添加标头。
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
另外,检查SharedPreferences
是否收到了令牌。你看起来很奇怪。