自定义拦截器,实现 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();
}
private Request getLoginRequest() {
return new Request.Builder()
.url("登录api地址")
.post(new FormBody.Builder()
.add("username", "用户名")
.add("password", "密码")
.build())
.build();
}
|