简体   繁体   English

如何使用 okhttp 客户端在 Android 中重定向发布请求

[英]How to redirect a post request in Android using okhttp client

I have gone through this answer OkHttp doesn't redirect POST requests when used with retrofit in order to redirect a post request, more specifically when I got 307 responses.我已经完成了这个答案OkHttp 与 retrofit 一起使用时不会重定向 POST 请求以重定向发布请求,更具体地说,当我收到 307 响应时。 I have created an Interceptor called RedirectURL in order to redirect the requests but it does not work.我创建了一个名为 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 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();
}

Your example is creating a new GET request without the body.您的示例是创建一个没有正文的新 GET 请求。

The latest OkHttp version should be automatically following a redirect with a 307 response.最新的 OkHttp 版本应该会自动跟随带有 307 响应的重定向。

https://github.com/square/okhttp/pull/5990/files https://github.com/square/okhttp/pull/5990/files

Are you testing with a recent version eg 4.9.1?您是否正在使用最新版本(例如 4.9.1)进行测试?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM