在Android Studio中使用Retrofit 2.0发送Header中的认证令牌,您可以按照以下步骤进行操作:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
public interface ApiService {
@Headers("Authorization: Bearer {token}")
@GET("your/api/endpoint")
Call<YourResponseModel> yourApiMethod(@Path("token") String token);
}
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "Bearer your_token_here");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://your.api.base.url/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<YourResponseModel> call = apiService.yourApiMethod("your_token_here");
call.enqueue(new Callback<YourResponseModel>() {
@Override
public void onResponse(Call<YourResponseModel> call, Response<YourResponseModel> response) {
if (response.isSuccessful()) {
// 处理成功响应
} else {
// 处理错误响应
}
}
@Override
public void onFailure(Call<YourResponseModel> call, Throwable t) {
// 处理请求失败
}
});
请注意,上述代码中的"your_token_here"需要替换为您实际的认证令牌。
推荐的腾讯云相关产品:腾讯云移动推送(https://cloud.tencent.com/product/tpns)可以用于在移动应用中实现消息推送功能。
希望以上信息能对您有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云