改造+基本认证

Fel*_* A. 5 android basic-authentication retrofit2

我已经使用基本身份验证实现了改造,我在登录请求时发送@header,但是当我调用一些经过身份验证的请求时,它返回401(未授权).

我如何实现它通用?或者我总是需要用@header调用我的身份验证请求?

@GET("user")
Call<User> getUserByEmail(@Query("email") String email, @Header("Authorization") String authorization);
Run Code Online (Sandbox Code Playgroud)

当我通过电子邮件调用Get User时(我对用户进行身份验证)...

@PUT("usuario/{userId}/")
Call<User> putUserById(@Path("userId") Integer id, @Body User user);
Run Code Online (Sandbox Code Playgroud)

当我调用Put用户时(我需要进行经过身份验证的请求).

我的改造班......

public class NetworkService {
private NetworkAPI networkAPI;
private OkHttpClient okHttpClient;

public NetworkService() {
    okHttpClient = buildClient();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfig.HOST)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    networkAPI = retrofit.create(NetworkAPI.class);
}

public NetworkAPI getAPI() {
    return networkAPI;
}

private OkHttpClient buildClient() {

    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            return response;
        }
    });

    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //this is where we will add whatever we want to our request headers.
            Request request = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .build();
            return chain.proceed(request);
        }
    });

    return builder.build();
}
}
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

Ras*_*iri 2

在 NetworkService 中使用 @Header("Authorization") 字符串授权

 Request request = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "AuthorizationValue")
                    .build();
Run Code Online (Sandbox Code Playgroud)