Retrofit 刷新token
package com.cmmboy.lib_basic.network;
import com.cmmboy.lib_basic.BuildConfig;
import com.cmmboy.lib_basic.sp.UserSharedPre;
import com.cmmboy.lib_basic.utils.LogUtils;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitManagement3 {
private static final long READ_TIMEOUT = 6000;
private static final long WRITE_TIMEOUT = 6000;
private static final long CONNECT_TIMEOUT = 6000;
private final Map mServiceMap = new ConcurrentHashMap();
private RetrofitManagement3() {
}
public static RetrofitManagement3 getInstance() {
return RetrofitHolder.mRetrofitManagement;
}
private static class RetrofitHolder {
private static final RetrofitManagement3 mRetrofitManagement = new RetrofitManagement3();
}
/**
* 打印请求消息
*
* @param request 请求的对象
*/
private String getRequestInfo(Request request) {
String str = "";
if (null == request) {
return str;
}
RequestBody requestBody = request.body();
if (null == requestBody) {
return str;
}
try {
Buffer bufferedSink = new Buffer();
requestBody.writeTo(bufferedSink);
Charset charset = StandardCharsets.UTF_8;
str = bufferedSink.readString(charset);
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
/**
* 打印返回消息
*
* @param response 返回的对象
*/
private String getResponseInfo(Response response) {
String str = "";
if (null == response || !response.isSuccessful()) {
return str;
}
ResponseBody responseBody = response.body();
if (null == responseBody) {
return str;
}
long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
try {
// Buffer the entire body.
source.request(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
Buffer buffer = source.getBuffer();
Charset charset = StandardCharsets.UTF_8;
if (contentLength != 0) {
str = buffer.clone().readString(charset);
}
return str;
}
private Retrofit createRetrofit(String url) {
// 请求头拦截器,一般用于自行处理签名
Interceptor requestInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request1 = chain.request();
LogUtils.d("请求参数拦截1===>", request1 + "");
LogUtils.d("请求参数拦截[请求格式]===>", request1.method() + "");
LogUtils.d("请求参数拦截[请求参数]===>", getRequestInfo(request1));
if (request1.method().equals("POST")) {
LogUtils.d("请求参数拦截[请求格式结果]===>", "POST");
}
// 配置请求头
Request request = chain.request().newBuilder()
.header("token", UserSharedPre.getInstance().getToken())
.build();
return chain.proceed(request);
}
};
// Response拦截器
Interceptor responseInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
try {
JSONObject tokenJson = new JSONObject(getResponseInfo(response));
int code = tokenJson.optInt("code");
LogUtils.d("Response拦截器[返回参数]===>", code + "");
if (code == 401) {
LogUtils.d("登录失效,重新登录===>", code + "");
// ARouter.getInstance().build("/login/LoginActivityForBusiness").navigation();
//使用新的Token,创建新的请求
Request newRequest = chain.request().newBuilder()
.header("token", getNewToken())
.build();
return chain.proceed(newRequest);
}
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
//请求数据拦截器
.addInterceptor(requestInterceptor)
//返回数据拦截器
.addInterceptor(responseInterceptor)
// .addInterceptor(new HeaderInterceptor())
// .addInterceptor(new FilterInterceptor())
// .retryOnConnectionFailure(true);
;
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(httpLoggingInterceptor);
}
OkHttpClient client = builder.build();
return new Retrofit.Builder()
.client(client)
// .baseUrl("https://www.wanandroid.com/")
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(new LiveDataCallAdapterFactory())
.build();
}
/**
* 重新获取Token
*
* @return
*/
private String getNewToken() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://172.170.88.128:8081/")
.addConverterFactory(GsonConverterFactory.create())
.build();
retrofit2.Response tokenJson = null;
try {
tokenJson = retrofit.create(TestApi.class).login2(body).execute();
} catch (IOException e) {
e.printStackTrace();
}
String token = "";
try {
JSONObject tokenObject = new JSONObject(tokenJson.body().toString());
token = tokenObject.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.d("刷新后的Token1:", tokenJson.body().toString());
LogUtils.d("刷新后的Token:", token);
UserSharedPre.getInstance().setToken(token);
return token;
}
public T create(Class service) {
return createRetrofit("http://172.170.88.128:8081/").create(service);
}
T getService(Class clazz) {
return getService(clazz, HttpConfig.BASE_URL_WEATHER);
}
@SuppressWarnings("unchecked")
T getService(Class clazz, String host) {
T value;
if (mServiceMap.containsKey(host)) {
Object obj = mServiceMap.get(host);
if (obj == null) {
value = createRetrofit(host).create(clazz);
mServiceMap.put(host, value);
} else {
value = (T) obj;
}
} else {
value = createRetrofit(host).create(clazz);
mServiceMap.put(host, value);
}
return value;
}
}