[英]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.