Retrofit File Converter

Retrofit File Converter,第1张

val retrofit: Retrofit by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(FileConverterFactory())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okHttpClient)
            .build()
}
class FileConverterFactory : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type,
        annotations: Array,
        retrofit: Retrofit
    ): Converter? {
        if (type == File::class.java) {
            return FileConverter()
        }
        return super.responseBodyConverter(type, annotations, retrofit)
    }

    private class FileConverter : Converter {

        override fun convert(value: ResponseBody): File {
            return getFile(value)
        }

        fun getFile(responseBody: ResponseBody): File {
            return if (responseBody is FileResponseBody) {
                responseBody.file
            } else try {
                val field = responseBody.javaClass.getDeclaredField("delegate")
                field.isAccessible = true
                val delegate = field.get(responseBody) as ResponseBody
                getFile(delegate)
            } catch (throwable: Throwable) {
                throw RuntimeException("响应体中没有记录文件信息!或者没有使用Tag标记File类型的参数!", throwable)
            }
        }

    }


}
class FileResponseBody(val file: File, private val contentType: MediaType?) : ResponseBody() {

    override fun contentLength(): Long = file.length()

    override fun source(): BufferedSource = file.source().buffer()

    override fun contentType(): MediaType? = contentType

}

在Okhttp中 添加一个文件Interceptor 将ResponseBody转换为FileResponseBody

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/886197.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存