Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

retrofit / okhttp wrong serialization of ByteArray (toString()) in kotlin #4279

Open
rowi1de opened this issue Jan 6, 2025 · 0 comments
Open

Comments

@rowi1de
Copy link

rowi1de commented Jan 6, 2025

Using Retrofit 2.11.0 and okhttp 4.12.0 in kotlin will end up in wrong sterilization of binary data as it will use toString() having the [] of the string representation in the body

Image

  val okHttpClient =
        OkHttpClient
          .Builder()
          .addInterceptor(httpLoggingInterceptor())
          .build()
      val retrofit =
        Retrofit
          .Builder()
          .baseUrl(config.url)
          .client(okHttpClient)
         // FIXME should not be needed  .addConverterFactory(ByteArrayConverterFactory())
          .build()
      retrofit.create(ApiClient::class.java)



private fun httpLoggingInterceptor(): HttpLoggingInterceptor {
  val logger = LogManager.getLogger(ApiClient::class.java)
  val logging = HttpLoggingInterceptor { logger.info(it) }
  logging.setLevel(HttpLoggingInterceptor.Level.BODY)
  logging.redactHeader("Authorization")
  logging.redactHeader("x-api-key")
  return logging
}

interface ApiClient {
  @POST("//binary")
  @Headers("Content-Type: application/octet-stream")
  fun binary(
  ): Call<ResponseBody>

// the workaround
class ByteArrayConverterFactory : Converter.Factory() {
  override fun requestBodyConverter(
    type: Type,
    parameterAnnotations: Array<Annotation>,
    methodAnnotations: Array<Annotation>,
    retrofit: Retrofit,
  ): Converter<ByteArray, RequestBody>? {
    if (type == ByteArray::class.java) {
      return Converter { value ->
        RequestBody.create(
          "application/octet-stream".toMediaTypeOrNull(),
          value,
        )
      }
    }
    return null
  }

  override fun responseBodyConverter(
    type: Type,
    annotations: Array<Annotation>,
    retrofit: Retrofit,
  ): Converter<ResponseBody, ByteArray>? {
    if (type == ByteArray::class.java) {
      return Converter { value ->
        value.use { it.bytes() }
      }
    }
    return null
  }
}
@rowi1de rowi1de changed the title retrofit / okhttp wrong seriliazation of ByteArray (toString()) in kotlin retrofit / okhttp wrong serialization of ByteArray (toString()) in kotlin Jan 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant