如何使用改造将不记名令牌添加到表单数据到 POST 到网络 API

How do I add bearer token to a form data using retrofit to POST to a web API

我是改装新手,在Java中也有点生疏。我正在尝试 post 使用改造 post 表单数据到使用 API 的 Web 服务。 API 需要 Bearer 令牌来验证和接受数据。问题是我不知道该怎么做。下面是我的代码。

我的ApiClient.javaclass

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 中得到了 'Unauthenticated' 的响应。

我的日志

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);