我们不需要以auth的形式传递所有属性,改型本身可以处理这个问题,我们只需要传递CONSUMER\u密钥、CONSUMER\u SECRET、ACCESS\u令牌和TOKEN\u SECRET。
通过以下方式
this
ApiUtils类将是这样的,
科特林
class ApiUtils {
companion object {
fun getAPIService(): APIService? {
val consumer = OkHttpOAuthConsumer(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET)
consumer.setTokenWithSecret(BuildConfig.ACCESS_TOKEN, BuildConfig.TOKEN_SECRET)
return RetrofitClient.getClient(BuildConfig.BASE_URL, consumer)?.create(APIService::class.java)
}
}
}
就业喜报
public class ApiUtils {
private ApiUtils() {
}
private static final String BASE_URL = BuildConfig.BASE_URL;
public static APIService getAPIService() {
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET);
consumer.setTokenWithSecret(BuildConfig.ACCESS_TOKEN, BuildConfig.TOKEN_SECRET);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
return RetrofitClient.getClient(BASE_URL, client).create(APIService.class);
}
}
对于
改装客户端类
科特林
class RetrofitClient {
companion object {
private var retrofit: Retrofit? = null
private val gSON = GsonBuilder()
.setLenient()
.create()
fun getClient(baseUrl: String, consumer: OkHttpOAuthConsumer): Retrofit? {
val logging = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY
} else {
logging.level = HttpLoggingInterceptor.Level.NONE
}
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(60000, TimeUnit.SECONDS)
httpClient.writeTimeout(120000, TimeUnit.SECONDS)
httpClient.readTimeout(120000, TimeUnit.SECONDS)
httpClient.retryOnConnectionFailure(true)
httpClient.addInterceptor(SigningInterceptor(consumer))
httpClient.addInterceptor { chain ->
val request = chain.request()
val requestBuilder = request.newBuilder()
.header(HEADER_CONTENT_TYPE_KEY, PreferenceHandler.getContentType())
.header(HEADER_ACCEPT_KEY, PreferenceHandler.getAcceptType())
.header(HEADER_CACHE_CONTROL_KEY, PreferenceHandler.getCacheControl())
val modifiedRequest = requestBuilder.build()
chain.proceed(modifiedRequest)
}
httpClient.addNetworkInterceptor(logging)
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gSON))
.client(httpClient.build())
.build()
}
return retrofit
}
}
}
Android java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl,OkHttpClient client) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}