改造 OkHttp 连接错误时流意外结束

Sre*_*ari 5 https android okhttp retrofit2

我正在使用以下依赖项(Retrofit 和 OkHttp)。

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
Run Code Online (Sandbox Code Playgroud)

下面是我的代码:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(cache_interceptor)
                .cache(cache)
                .connectTimeout(AppConstants.TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(AppConstants.TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(AppConstants.TIME_OUT, TimeUnit.SECONDS)
                .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT))
                .retryOnConnectionFailure(false)
                .build();

return new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BuildConfig.BASE_URL).build();

private final Interceptor cache_interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request().newBuilder().addHeader("Connection", "close").build();
            return chain.proceed(request);
        }
    };
Run Code Online (Sandbox Code Playgroud)

URL 是https之一,指向AWS S3实例。

但我收到以下httpsURL 端点错误。

java.io.IOException:连接上的流意外结束{s3.amazonaws.com:443,proxy=DIRECT hostAddress=s3.amazonaws.com/XX.XXX.XXX.XX:443 cipherSuite=none protocol=http/1.1}

浏览了类似的线程,如Github 讨论 1Github 讨论 2 ,但找不到解决方案。

如果我用http替换https,也没有问题或错误!

知道可能是什么原因造成的吗?


编辑1:

由于我不确定是什么导致了问题,我只是从 Retrofit 注释掉了 OK Http 作为客户端。

令人惊讶的是没有抛出错误。!

return new Retrofit.Builder()
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BuildConfig.BASE_URL).build();
Run Code Online (Sandbox Code Playgroud)

任何人想对这个问题做出贡献,请发表评论或写一个答案。非常值得赞赏!

Sre*_*ari 2

自从我编辑我的问题并贴出注释以供其他人给出有效答案以来,已经有一个多月了。到目前为止,SO 还没有提供解决方案,我正在写下该解决方案以供将来参考。

虽然下面的内容并不完全是我想要的,但我可以通过避免得到预期的响应OkHttpClient

这是我提到的有问题的版本。 在未来的发行版本中可能会或可能不会出现相同的问题。

是的,你没看错。避免OkHttpClient并尝试Retrofit单独使用。

return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BuildConfig.BASE_URL).build();
Run Code Online (Sandbox Code Playgroud)

尽管这阻止了获取 HTTP 日志,但我仍然能够获得HTTPHTTPS的成功响应。