我有一个令牌,我保存到sharedPreferences然后我得到该令牌并将其作为授权转发给Retrofit请求。这是我以下的代码,我曾经在我的改装请求中添加标题。
我需要添加以下标题: 的"授权" "承载" +令牌
public static Retrofit getClient(String token) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okClient = new OkHttpClient();
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
okClient.interceptors().add(chain -> {
Response response = chain.proceed(chain.request());
return response;
});
okClient.interceptors().add(chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
});
okClient.interceptors().add(logging);
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(Config.BASE_URL1)
.client(okClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
这是我如何将我的令牌发送到改装客户端
Retrofit retrofit = RetrofitClient.getClient("Bearer" + " " + authUser.getToken());
APIService mAPIService = retrofit.create(APIService.class);
但遗憾的是,服务器会回复无权限
消息答案 0 :(得分:7)
您可以在不使用拦截器的情况下将标头发送到服务器。只需在服务界面的方法声明中添加一个字段,如下所示:
@GET("my/orders/{id}")
Call<Order> getOrder(@Header("Authorization") String token,
@Path("id") int order_id);
然后创建一个Call
对象来发送请求,如下所示:
APIService apiService= retrofit.create(APIService.class);
Call<Order> call = apiService.getOrder(token, id);
call.enqueue(/*callback*/);
答案 1 :(得分:0)
尝试相同:
String credentials = "put your token here";
final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization",basic);
答案 2 :(得分:0)
在BaseCaller类中为您的标头添加方法,如下所示:
public HashMap<String, String> getHeaders() {
HashMap<String, String> headerHashMap = new HashMap<>();
headerHashMap.put("Content-Type", "application/x-www-form-urlencoded");
headerHashMap.put("time_zone_name", DateTimeHelper.getTimeZoneName());
headerHashMap.put("gmt_offset", DateTimeHelper.getGMTOffset());
return headerHashMap;
}
现在在服务类中为url创建一个方法,如:
@FormUrlEncoded
@POST("switch_user")
Call<JsonObject> switchUser(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> fields);
最后,在您的类调用方类中,按如下所示调用方法:
call = loginService.switchUser(getHeaders(), apiParams.mHashMap);
这会做有需要的:)