retrofit 上传加密String数据(服务端收到数据多加一对引号,转义字符)

使用DES加密上传JSON数据:

服务器需要数据:{"aa":"bb"}

加密后提交到服务器: 解密后 “{\"aa\":\"bb\"}"

解决方法:

自定义GsonConverterFactory:

class CustomGsonConverterFactory private constructor(private val gson: Gson) : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type?, annotations: Array?,
        retrofit: Retrofit?
    ): Converter? {
        val adapter = gson.getAdapter(TypeToken.get(type!!))
        return CustomGsonResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array?, methodAnnotations: Array?, retrofit: Retrofit?
    ): Converter<*, RequestBody>? {
        return CustomGsonRequestBodyConverter()
    }

    companion object {

        fun create(): CustomGsonConverterFactory {
            return create(Gson())
        }

        /**
         * Create an instance using `gson` for conversion. Encoding to JSON and
         * decoding from JSON (when no charset is specified by a header) will use UTF-8.
         */
        // Guarding public API nullability.
        fun create(gson: Gson?): CustomGsonConverterFactory {
            if (gson == null) throw NullPointerException("gson == null")
            return CustomGsonConverterFactory(gson)
        }
    }
}

自定义:GsonRequestBodyConverter
internal class CustomGsonRequestBodyConverter   : Converter {

    @Throws(IOException::class)
    override fun convert(value: T): RequestBody {

        val bytes = value.toString().toByteArray(charset(HeadInput.PROTOCOL_CHARSET))
        val encrypt = DESUtil.encrypt(bytes, HeadInput.KEY_STRING.toByteArray(charset(HeadInput.PROTOCOL_CHARSET)))

        return RequestBody.create(MEDIA_TYPE, encrypt)
    }

    companion object {
        private val MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8")
    }
}

 

 

你可能感兴趣的:(android)