cn.blankcat.openapi.RetrofitManager Maven / Gradle / Ivy
package cn.blankcat.openapi;
import cn.blankcat.config.BotConfig;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.util.concurrent.TimeUnit;
public class RetrofitManager {
private RetrofitManager(){}
private static final Logger logger = LoggerFactory.getLogger("retrofitManager");
private enum Singleton {
INSTANCE;
private Retrofit retrofit;
Singleton() {
retrofit = new Retrofit.Builder()
.baseUrl(BotConfig.DEFAULT.getBaseUrl())
.addConverterFactory(JacksonConverterFactory.create())
.client(getOkHttpClient(BotConfig.DEFAULT.formatBetterToken()))
.build();
}
public static Retrofit getInstance() {
return INSTANCE.retrofit;
}
public static void setInstance(Retrofit retrofit) {
INSTANCE.retrofit = retrofit;
}
}
/**
* @return 获得一个Retrofit单例对象
*/
public static Retrofit getInstance() {
return Singleton.getInstance();
}
/**
* 根据默认配置设置全局Retrofit单例
*/
public static void setInstance() {
Singleton.setInstance(new Retrofit.Builder()
.baseUrl(BotConfig.DEFAULT.getBaseUrl())
.addConverterFactory(JacksonConverterFactory.create())
.client(getOkHttpClient(BotConfig.DEFAULT.formatBetterToken()))
.build());
}
/**
* 根据用户提供的Retrofit对象设置全局Retrofit单例
* @param retrofit 要设置的Retrofit对象
*/
public static void setInstance(Retrofit retrofit) {
Singleton.setInstance(retrofit);
}
/**
* 根据用户提供的服务器地址和token设置全局Retrofit单例
* @param baseUrl 要连接的服务器地址
* @param token 要添加的token
*/
public static void setInstance(String baseUrl, String token) {
Singleton.setInstance(new Retrofit.Builder()
.baseUrl(baseUrl)
.client(getOkHttpClient(token))
.addConverterFactory(JacksonConverterFactory.create())
.build());
}
private static OkHttpClient getOkHttpClient(String token) {
return new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("Authorization", token)
.build();
return chain.proceed(request);
})
.addInterceptor((chain) -> {
Response response = chain.proceed(chain.request());
MediaType mediaType = response.body().contentType();
String responseString = response.body().string();
if (response.code() > 209) {
logger.warn("请求错误, 错误内容为:{}", responseString);
}
return response.newBuilder().body(ResponseBody.create(mediaType, responseString)).build();
})
.readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.connectTimeout(3, TimeUnit.SECONDS)
.build();
}
}