2 years ago

#61807

test-img

Max Michel

Handle application/pdf content type with Retrofit2

I have an API call to a server which gives me a response of type application/pdf. So far, nothing out of the ordinary.

The issue I am having is that I have a Retrofit instance with a MoshiConverterFactory hence it has no intention of handling such a response. I initially thought that adding a ScalarConverterFactory could help solve the issue but the response isn't a text/plain response or other types similar.

I'm not at all against writing a custom converter factory to handle this but I feel like handling a PDF response with retrofit would be more common than it seems to be.

I have no code to show apart from the api function and how I call it but I don't think this would help much:

// API pdf call
@GET("core/GetPDF")
    fun getPdf(@Query("file") fileGuid: String, @Query("fileName") fileName: String): Call<ResponseBody>

// --------------- Repository implementation to call the API
override fun getPdf(request: Pair<String, String>): InputStream? {
    val response = api.getPdf(request.first, request.second).execute()
    Timber.i("response: $response")

    return response.body()?.byteStream()
}

With this code, I am greeted with a nice com.squareup.moshi.JsonEncodingException: Use JsonReader.setLenient(true) to accept malformed JSON at path $

The way my retrofit is built is using Dependency Injection (Dagger/Hilt) and looks like this:

@Provides
fun provideApi(
    moshi: Moshi,
    client: OkHttpClient,
    @ApiUrl url: String
): WebApi {
    val httpClient = client.newBuilder()
        .build()

    return Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .client(httpClient)
        .build()
        .create(WebApi::class.java)
}

If anyone has any tips or directions to go to handle reading PDFs with Retrofit, that would be greatly appreciated!

android

pdf

retrofit2

converters

0 Answers

Your Answer

Accepted video resources