代码拉取完成,页面将自动刷新
之前版本无法正确处理 301、302、307 等重定向请求,而且 okhttp 和 httpclient 默认处理方式又有所不同,造成很多重定向相关的问题。
以下是新版本对重定向处理的办法
默认自动触发重定向,重定向的请求日志如下:
[Forest] Request (okhttp3):
[Redirect]: From POST http://localhost:59006/ -> 301
POST http://localhost:59006/b HTTP
拦截器的 onRedirection
方法会在重定向地址转移请求发送前触发,以此获得以一次的Request和Response对象,
即返回 301、302 等状态码的响应对象。
同时,还能对地址转移请求做修改
public class RedirectInterceptor implements Interceptor<Object> {
@Override
public void onRedirection(ForestRequest<?> redirectReq, ForestRequest<?> prevReq, ForestResponse<?> prevRes) {
// 获取转移前请求信息
String prevUrl = prevReq.getUrl();
// 获取转移前响应信息
String location = prevRes.getHeader("Location");
// 对地址转移请求做修改
redirectReq.addBody("body", "xxx");
}
}
除了拦截器可以截取转移前请求和响应对象外,也可以通过 OnRedirection 回调函数接口进行同样的操作:
// OnRedirection 为重定向回调函数,会在url转移前触发
@Post("/")
ForestResponse<String> sendData(OnRedirection onRedirection);
... ...
ForestResponse<String> response = sendData((redirectReq, prevReq, prevRes) -> {
// 获取转移前请求信息
String prevUrl = prevReq.getUrl();
// 获取转移前响应信息
String location = prevRes.getHeader("Location");
// 对地址转移请求做修改
redirectReq.addBody("body", "xxx");
});
以上是第一种模式,即自动重定向模式,也可以关闭自动重定向, 可以有两种方式打开和关闭重定向:
forest:
... ...
# 全局自动重定向开关,默认为开启
auto-redirection: false
@Redirection
注解,它能控制到具体的接口和方法// 打开整个接口方法的自动重定向
@Redirection
public interface MyTestClient {
// 关闭某个方法的重定向
@Redirection(false)
@Get("/")
String getData();
... ...
}
// 关闭整个接口方法的自动重定向
@Redirection(false)
public interface MyTestClient {
// 打开某个方法的重定向
@Redirection
@Get("/")
String getData();
... ...
}
// 关闭了自动重定向
// 需要将方法返回值设为 ForestResponse 类型
@Redirection(false)
@Get("/")
ForestResponse<String> getData();
通过 ForestReposne.isRedirection() 判断是否需要重定向转移,再通过 ForestResponse.redirectionRequest() 获取重定向Url转移请求对象。
// 调用接口获得转移前的响应对象
ForestResponse<String> response = client.getData();
// 判断是否需要重定向转移
if (response.isRedirection()) {
// 获得转移请求对象,并执行
String result = response.redirectionRequest().executeAsString();
... ...
}
这时,拦截器和 OnRedirection 回调函数同样有效。