改造和OkHttp基本认证 [英] Retrofit and OkHttp basic authentication

查看:107
本文介绍了改造和OkHttp基本认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将基本身份验证(用户名和密码)添加到翻新的OkHttp客户端.这是我到目前为止的代码:

I am trying to add basic authentication (username and password) to a Retrofit OkHttp client. This is the code I have so far:

private static Retrofit createMMSATService(String baseUrl, String user, String pass) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    return retrofit;
}

我正在使用Retrofit 2.2,并且本教程建议使用,但该类不可用. 添加凭据的正确位置在哪里?我是否必须将它们添加到我的拦截器,客户端或改造对象中?那我该怎么做?

I am using Retrofit 2.2 and this tutorial suggests using AuthenticationInterceptor, but this class is not available. Where is the correct place to add the credentials? Do I have to add them to my interceptor, client or Retrofit object? And how do I do that?

推荐答案

查找解决方案

1.编写一个拦截器类

1.Write a Interceptor class

import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BasicAuthInterceptor implements Interceptor {

    private String credentials;

    public BasicAuthInterceptor(String user, String password) {
        this.credentials = Credentials.basic(user, password);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request authenticatedRequest = request.newBuilder()
            .header("Authorization", credentials).build();
        return chain.proceed(authenticatedRequest);
    }

}

2.最后,将拦截器添加到OkHttp客户端

2.Finally, add the interceptor to an OkHttp client

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new BasicAuthInterceptor(username, password))
    .build();

这篇关于改造和OkHttp基本认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆