为什么创建OkHttpClient实例需要这么长时间?

时间:2019-04-13 20:16:35

标签: java android okhttp3 android-2.3-gingerbread

我已经在需要2.3秒钟的Android 2.3 Gingerbread设备上获得了这段代码。

我在远离UI线程的异步任务中运行它(但在我运行它的地方没有影响)

long startTime = System.nanoTime();
OkHttpClient client = new OkHttpClient.Builder()
        .followRedirects(false)
        .build();
long clientBuilt = System.nanoTime();
Log.d("API", String.format("Created OkHttpClient, it took %f milliseconds", (clientBuilt - startTime)/1000000d));
D/API: Created OkHttpClient, it took 30814.207720 milliseconds

我具有此Android版本的OkHttp的最新版本: 'com.squareup.okhttp3:okhttp:3.12.0'

编辑:

应用马丁建议的代码后: .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT))

并运行对服务器的调用,我得到一个例外:

java.io.IOException: unexpected end of stream on Connection{motoactv.com:443, proxy=DIRECT hostAddress=motoactv.com/69.10.180.44:443 cipherSuite=none protocol=http/1.1}
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:208)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        ...
Caused by: java.io.EOFException: \n not found: limit=0 content=…
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:236)
        at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)

1 个答案:

答案 0 :(得分:0)

这种旧API尚不支持SNI;强制使用纯文本HTTP可能会有所帮助:

OkHttpClient client = new OkHttpClient.Builder()
    .connectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT))
    .followRedirects(false)
    .build();

踏入OkHttpClient.Builder还应该告诉您确切的位置。