【问题标题】:Call Retrofit2 + Decrypt + Json conversor调用 Retrofit2 + Decrypt + Json 转换器
【发布时间】:2018-08-22 16:25:28
【问题描述】:
我在kotlin 中使用retrofit2,我需要获取json 和这个encrypted 的内容,我知道要转换json 只需使用JacksonConverterFactory(直到这个部分运行良好)但在此之前添加了encryption,我不知道如何处理这个,我需要创建自己的转换器吗?有没有人想告诉我的?
我目前的改造要求
val retrofit = Retrofit.Builder()
.baseUrl("http://100.1.1.100/")
.addConverterFactory(JacksonConverterFactory.create())
.client(httpClient.build())
.build()
我已经有我的功能(工作)来解密:
CryptAES.decrypt(value))
【问题讨论】:
标签:
android
json
encryption
kotlin
retrofit2
【解决方案1】:
这可以通过创建一个解密interceptor来完成:
class DecryptInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain
.run { proceed(request()) }
.let { response ->
return@let if (response.isSuccessful) {
val body = response.body()!!
val contentType = body.contentType()
val charset = contentType?.charset() ?: Charset.defaultCharset()
val buffer = body.source().apply { request(Long.MAX_VALUE) }.buffer()
val bodyContent = buffer.clone().readString(charset)
response.newBuilder()
.body(ResponseBody.create(contentType, bodyContent.let(::decryptBody)))
.build()
} else response
}
private fun decryptBody(content: String): String {
//decryption
return content
}
}
设置:
val httpClient = OkHttpClient().newBuilder()
httpClient.addInterceptor(DecryptInterceptor())
val retrofit = Retrofit.Builder()
.baseUrl("http://100.1.1.100/")
.addConverterFactory(JacksonConverterFactory.create())
.client(httpClient.build())
.build()