如何在retrofit2中正确处理重定向作为响应

时间:2018-05-20 19:31:20

标签: java android retrofit2

我正在使用API,在成功创建具有308请求的资源时返回POST?如何使用retrofit2处理此问题?

或者API不应该返回308

2 个答案:

答案 0 :(得分:0)

如下所示创建Interceptor,然后调用addInterceptor(getRedirectInterceptor())(在OkHttpClient.Builder实例上)

protected Interceptor getRedirectInterceptor() {
    return new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            okhttp3.Response response = chain.proceed(request);
            if (response.code() == 308) {
                request = request.newBuilder()
                        .url(response.header("Location"))
                        .build();

                response = chain.proceed(request);
            }

            return response;
        }
    };
}

答案 1 :(得分:0)

onResponse

if(response.code() == 308)
{
    //created done
}
 else 
{
    //not done
}