[英]How to redirect a post request in Android using okhttp client
我已经完成了这个答案OkHttp 与 retrofit 一起使用时不会重定向 POST 请求以重定向发布请求,更具体地说,当我收到 307 响应时。 我创建了一个名为 RedirectURL 的拦截器来重定向请求,但它不起作用。
private static Interceptor redirectRequest() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(chain.request());
if (response.code() == 307) {
Log.d(TAG, "intercept: is true"+response.code());
request = request.newBuilder()
.url(response.header("Location"))
.build();
response = chain.proceed(request);
}
return response;
}
};
}
OkkHttp
private OkHttpClient okHttpClient() {
RepositoryService repositoryService = new RepositoryService(context);
return new OkHttpClient.Builder()
// .cache(cache())
.followRedirects(true)
.followSslRedirects(true)
.connectTimeout(5, TimeUnit.MINUTES) // re-request if package is drop or TimeOut reach 60 seconds
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.addInterceptor(httpsLoggingInterceptor()) // used if network off OR on
.addInterceptor(redirectRequest())
.addNetworkInterceptor(repositoryService.networkInterceptor())
.build();
}
您的示例是创建一个没有正文的新 GET 请求。
最新的 OkHttp 版本应该会自动跟随带有 307 响应的重定向。
https://github.com/square/okhttp/pull/5990/files
您是否正在使用最新版本(例如 4.9.1)进行测试?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.