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<String, Object> mServiceMap = new ConcurrentHashMap<>();
private RetrofitManagement3() {
}
public static RetrofitManagement3 getInstance() {
return RetrofitHolder.mRetrofitManagement;
}
private static class RetrofitHolder {
private static final RetrofitManagement3 mRetrofitManagement = new RetrofitManagement3();
}
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;
}
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 {
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);
}
};
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 + "");
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)
;
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(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(new LiveDataCallAdapterFactory())
.build();
}
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<JsonObject> 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> T create(Class<T> service) {
return createRetrofit("http://172.170.88.128:8081/").create(service);
}
<T> T getService(Class<T> clazz) {
return getService(clazz, HttpConfig.BASE_URL_WEATHER);
}
@SuppressWarnings("unchecked")
<T> T getService(Class<T> 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;
}
}