具有followRedirects(false)的OkHttpClient返回body = null的响应

时间:2017-07-10 08:03:15

标签: java android retrofit2 okhttp3

我正在使用改装来处理http请求,当我发起一个帖子请求时,响应来自另一个网址,并且得到500个错误代码,而不是我将 followRedirects 设置为false ,为了防止重定向,但现在我得到了响应,其中响应正文为空, rawResponse 包含此消息 code = 302 message = Found 。我使用Postman尝试了相同的请求并且工作正常。

这是我的改装界面工厂类

 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

0 个答案:

没有答案