Java 带有followRedirects(false)的OkHttpClient返回body=null的响应
我正在对http请求使用改型,当我启动post请求时,响应来自另一个url,得到了500个错误代码,而我将followRedirects设置为false,以防止重定向,但现在我得到了响应,其中,响应正文为空,并且rawResponse包含此消息code=302 message=Found。我用邮递员试过同样的请求,效果很好 这是我的改装接口工厂类Java 带有followRedirects(false)的OkHttpClient返回body=null的响应,java,android,retrofit2,okhttp3,Java,Android,Retrofit2,Okhttp3,我正在对http请求使用改型,当我启动post请求时,响应来自另一个url,得到了500个错误代码,而我将followRedirects设置为false,以防止重定向,但现在我得到了响应,其中,响应正文为空,并且rawResponse包含此消息code=302 message=Found。我用邮递员试过同样的请求,效果很好 这是我的改装接口工厂类 class Factory { final static OkHttpClient.Builder httpClient = new OkH
class Factory {
final static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false);
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
private static NetworkApi.Factory serverApi;
private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
public static NetworkApi getApi() {
if (BuildConfig.DEBUG){
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder()
.addHeader("Content-Type", "application/json");
return chain.proceed(builder.build());
}
});
httpClient.interceptors().add(interceptor);
}
if (serverApi == null){
serverApi = new NetworkApi.Factory();
}
return serverApi.retrofit.create(NetworkApi.class);
}
}
改装库版本是2.1.0,那么到底是什么问题?您告诉okhttp不要自动跟踪302重定向,这样您就可以得到返回给您的重定向响应。问题是响应正文为空。是的,重定向是这样工作的-它们使用头将http客户端指向另一个位置。您的建议是什么?我如何检索响应体,或者允许okhttp为您处理重定向,或者首先将您的请求提交到真正的目标URL。那么到底是什么问题呢?您告诉okhttp不要自动跟踪302重定向,这样您就可以得到返回给您的重定向响应。问题是响应正文为空。是的,重定向是这样工作的-它们使用头将http客户端指向另一个位置。您的建议是什么?我如何检索响应体?首先,允许okhttp为您处理重定向,或者将您的请求提交到真正的目标URL。