我正在开发一个应用程序,我必须通过 HTTPS 与具有自签名证书的嵌入式 IoT 产品进行通信。我成功设置 OkHttp 以使用自签名证书,并通过 Retrofit2 使用 RxCallAdapters 进行网络调用。
嵌入式产品一次只能处理一个连接,所以我将底层 OkHttp 实例配置为只允许一个连接(据我所知,也许有更好的方法)。
如果我只发出 GET 请求,则握手成功完成,并且连接对于整个请求序列保持打开状态。嵌入式产品在 5 秒不活动后关闭连接,因此预计我必须每隔一段时间重做一次握手。
在执行 PUT 和 POST 请求时问题开始出现。当请求流从一种请求类型更改为另一种请求类型时,或者实际上任何时候请求是 PUT 或 POST 时,OkHttp 似乎都不会保持现有连接打开。例如:
握手- 得到 - 得到 - 得到 -握手- 放 -握手- 得到......等等。
如何强制 OkHttp 在不同类型的请求之间保持连接打开?我知道这无关紧要,但似乎与响应代码有关。嵌入式设备上的 REST API 为 GET 提供 200,为 POST 提供 201,为 PUT 提供 204。
这是我用来配置 OkHttp 和我的改造实例的相关代码:
@Provides
@Singleton
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
val httpLoggingInterceptor = HttpLoggingInterceptor { message -> Timber.tag("OkHttp").d(message) }
setLogLevel(httpLoggingInterceptor)
return httpLoggingInterceptor
}
private fun setLogLevel(httpLoggingInterceptor: HttpLoggingInterceptor) {
if (BuildConfig.DEBUG) {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
} else {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
}
}
@Provides
@Singleton
fun provideContentTypeHeaderInterceptor(): Interceptor {
return Interceptor { chain ->
val originalRequest = chain.request()
val requestBuilder = originalRequest.newBuilder()
requestBuilder.header("Content-Type", "application/json")
chain.proceed(requestBuilder.build())
}
}
@Provides
@Singleton
@LocalOkHttpConnectionPool
fun provideLocalConnectionPool() = ConnectionPool(1, 5, TimeUnit.SECONDS)
@Provides
@Singleton
@LocalOkHttpClient
fun provideLocalOkHttpClient(headerInterceptor: Interceptor,
httpLoggingInterceptor: HttpLoggingInterceptor,
@LocalOkHttpConnectionPool connectionPool: ConnectionPool,
context: Context): OkHttpClient {
val cf = CertificateFactory.getInstance("X.509")
val cert = context.getResources().openRawResource(R.raw.ca) // Place your 'my_cert.crt' file in `res/raw`
val ca = cf.generateCertificate(cert)
cert.close()
val keyStoreType = KeyStore.getDefaultType()
val keyStore = KeyStore.getInstance(keyStoreType)
keyStore.load(null, null)
keyStore.setCertificateEntry("ca", ca)
val tmfs = CompositeX509TrustManager.getTrustManagers(keyStore)
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, tmfs, null)
val hostNameVerifier = HostnameVerifier { hostname, session ->
return@HostnameVerifier true
}
val connectionSpec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.allEnabledCipherSuites()
.allEnabledTlsVersions()
.supportsTlsExtensions(true)
.build()
val connectionSpecs = mutableListOf(connectionSpec)
val okHttpClient = OkHttpClient.Builder()
.connectionSpecs(connectionSpecs)
.hostnameVerifier(hostNameVerifier)
.addInterceptor(headerInterceptor)
.addInterceptor(httpLoggingInterceptor)
.connectionPool(connectionPool)
.sslSocketFactory(sslContext.socketFactory, tmfs.first() as X509TrustManager)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build()
return okHttpClient
}
@Provides
@Singleton
@LocalRetrofit
fun provideLocalRetrofit(@LocalOkHttpClient okHttpClient: OkHttpClient,
gson: Gson): Retrofit {
return Retrofit.Builder().baseUrl(NetworkUtils.BASE_AUTH_URL)
.addConverterFactory(NullOnEmptyConverterFactory())
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
}