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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)