自定义拦截器,实现 intercept
方法
@Override
public Response intercept(Chain chain) throws IOException {
Request originalReq = chain.request();
Response originalResp = chain.proceed(originalReq);
ResponseBody body = originalResp.body();
MediaType mediaType = body.contentType();
String str = body.string();
// 判断是否登录过期
JSONObject json = JSONObject.parseObject(str);
if (HttpUtil.checkErrorCode(ErrorEnum.LOGIN_EXPIRED, json.getString("errorCode"))) {
originalResp.body().close();
Request loginRequest = getLoginRequest();
Response loginResponse = chain.proceed(loginRequest);
// 如果登录成功再重新发送原来的请求
if (loginResponse.isSuccessful()) {
List<String> cookies = loginResponse.headers("set-cookie");
if (!cookies.isEmpty()) {
String cookie = CookieUtil.encodeCookie(cookies);
CookieUtil.saveCookie(loginRequest.url().toString(), loginRequest.url().host(), cookie);
}
loginResponse.body().close();
return chain.proceed(originalReq);
}
}
// 重建原来的响应
return originalResp.newBuilder()
.body(ResponseBody.create(mediaType, str))
.build();
}
// 获取登录的request
private Request getLoginRequest() {
return new Request.Builder()
.url("登录api地址")
.post(new FormBody.Builder()
.add("username", "用户名")
.add("password", "密码")
.build())
.build();
}