retrofit icon indicating copy to clipboard operation
retrofit copied to clipboard

ScalarsConverterFactory is applied regardless Content-Type

Open snedbalek-paylocity opened this issue 1 year ago • 0 comments

By the documentation of ScalarsConverterFactory, I'd expect the converter to be applied only on text/plain:

A {@linkplain Converter.Factory converter} for strings and both primitives and their boxed types to {@code text/plain} bodies.

But that is ignored and it consumes even application/json as shown in this test case:

import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.http.GET

class RetrofitBug {
    @JvmField
    @Rule
    val server: MockWebServer = MockWebServer()

    internal interface Service {
        @GET("/path")
        fun foo(): Call<String>
    }

    @Test
    @Throws(Exception::class)
    fun test() {
        val retrofit = Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create())
            .build()
        val example = retrofit.create(
            Service::class.java
        )

        server.enqueue(
            MockResponse()
                .addHeader("Content-Type", "application/json")
                .setBody("\"Hi\"")
        )

        val call = example.foo()
        val response = call.execute()
        Assert.assertEquals("application/json", response.headers()["Content-Type"])
        Assert.assertEquals("Hi", response.body())
    }
}

The shared case won't fail if the factories are reversed:

            .addConverterFactory(MoshiConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())

But that has implications on body serialization. Is there a way how to restrict converter only to certain content type? Is this a bug? Should the docu be updated?

snedbalek-paylocity avatar Aug 20 '24 16:08 snedbalek-paylocity