【问题标题】:How to redirect a post request in Android using okhttp client如何使用 okhttp 客户端在 Android 中重定向发布请求
【发布时间】:2021-05-13 22:25:02
【问题描述】:

我已经通过这个答案OkHttp doesn't redirect POST requests when used with retrofit 来重定向一个帖子请求,更具体地说,当我收到 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();
}

【问题讨论】:

    标签: java retrofit okhttp interceptor


    【解决方案1】:

    您的示例是创建一个没有正文的新 GET 请求。

    最新的 OkHttp 版本应该会自动跟随带有 307 响应的重定向。

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

    您是否正在使用最新版本进行测试,例如4.9.1?

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多