[英]How do I add bearer token to a form data using retrofit to POST to a web API
我是 retrofit 的新手,在 Java 中也有点生疏。 我正在尝试使用 retrofit 发布表单数据,以使用 API 将其发布到 web 服务。 API 需要不记名令牌来验证和接受数据。 问题是我不知道如何 go 关于它。 下面是我的代码。
我的 ApiClient.java class
public class ApiClient {
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer ")
.build();
return chain.proceed(request);
}
}).addInterceptor(httpLoggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://xxxxxxx/")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getUserService(){
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
这是我的 UserService.java
public interface UserService {
@POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(@Body UserRequest userRequest);
}
使用上面的代码,我在我的 logcat 中得到了“未验证”的响应。
我的日志
I/okhttp.OkHttpClient: date: Mon, 14 Jun 2021 19:52:40 GMT
content-type: application/json
x-powered-by: PHP/7.4.20
cache-control: private, must-revalidate
x-ratelimit-limit: 60
x-ratelimit-remaining: 59
pragma: no-cache
expires: -1
I/okhttp.OkHttpClient: vary: Authorization
I/okhttp.OkHttpClient: {"message":"Unauthenticated."}
我需要帮助
您尚未在addHeader("Authorization", "Bearer ")
中传递令牌。 它应该是
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
String token = pref.getToken();
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
此外,您只在日志拦截器中记录正文。 尝试删除这一行httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.