How to download PDF file with Retrofit and Kotlin coroutines?

可紊 提交于 2019-12-02 08:30:02

You can change the return type of exportPdf to Call<ResponseBody> and then check the response code. If it's ok then read the body as a stream. If it's not then try to deserialize ExportResponse. It will look something like this I guess:

val response = restAdapter.apiRequest().execute()
if (response.isSuccessful) {
    response.body()?.byteStream()//do something with stream
} else {
    response.errorBody()?.string()//try to deserialize json from string
}

Update

Here is a complete listing of my test:

import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Url
import java.io.File
import java.io.InputStream

fun main() {
    val queries = buildQueries()
    check(queries, "http://127.0.0.1:5000/error")
    check(queries, "http://127.0.0.1:5000/pdf")
}

private fun check(queries: Queries, url: String) {
    val response = queries.exportPdf(HttpUrl.get(url)).execute()
    if (response.isSuccessful) {
        response.body()?.byteStream()?.saveToFile("${System.currentTimeMillis()}.pdf")
    } else {
        println(response.errorBody()?.string())
    }
}

private fun InputStream.saveToFile(file: String) = use { input ->
    File(file).outputStream().use { output ->
        input.copyTo(output)
    }
}

private fun buildRetrofit() = Retrofit.Builder()
    .baseUrl("http://127.0.0.1:5000/")
    .client(OkHttpClient())
    .build()

private fun buildQueries() = buildRetrofit().create(Queries::class.java)

interface Queries {
    @GET
    fun exportPdf(@Url url: HttpUrl): Call<ResponseBody>
}

and here is simple sever built with Flask:

from flask import Flask, jsonify, send_file

app = Flask(__name__)


@app.route('/')
def hello():
    return 'Hello, World!'


@app.route('/error')
def error():
    response = jsonify(error=(dict(body='some error')))
    response.status_code = 400
    return response


@app.route('/pdf')
def pdf():
    return send_file('pdf-test.pdf')

all works fine for me

Update 2

Looks like you have to write this in your Api:

@FormUrlEncoded
@Streaming // You can also comment this line.
@POST("export-pdf/")
fun exportPdf(
    @Field("token") token: String
): Call<ResponseBody>

Thanks to @AndreiTanana I found a mistake. A problem was in suspend in the request definition. All other requests retain their suspend modifier, but this request removed it. I changed the code so.

interface Api {
    @FormUrlEncoded
    @Streaming
    @POST("export-pdf/")
    fun exportPdf(
        @Field("token") token: String
    ): Call<ResponseBody>

    // Any another request. Note 'suspend' here.
    @FormUrlEncoded
    @POST("reject/")
    suspend fun reject(): RejectResponse
}

Then in it's implementation, ApiImpl:

class ApiImpl : Api {

    private val retrofit by lazy { ApiClient.getRetrofit().create(Api::class.java) }

    override fun exportPdf(
        token: String
    ): Call<ResponseBody> =
        retrofit.exportPdf(token)

    override suspend fun reject(): RejectResponse =
        // Here can be another instance of Retrofit.
        retrofit.reject()
}

Retrofit client:

class ApiClient {

    companion object {

        private val retrofit: Retrofit


        init {

            val okHttpClient = OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()

            val gson = GsonBuilder().setLenient().create()

            retrofit = Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .client(okHttpClient)
                // .addConverterFactory(GsonConverterFactory.create(gson)) - you can add this line, I think.
                .build()
        }

        fun getRetrofit(): Retrofit = retrofit
}

Interactor:

interface Interactor {
    // Note 'suspend' here. This is for coroutine chain.
    suspend fun exportPdf(
        token: String
    ): Call<ResponseBody>
}

class InteractorImpl(private val api: Api) : Interactor {
    override suspend fun exportPdf(
        token: String
    ): Call<ResponseBody> =
        api.exportPdf(token)
}

Then in fragment:

private fun exportPdf(view: View, token: String) {
    showProgress(view)
    launch(Dispatchers.IO) {
        try {
            val response = interactor.exportPdf(token).execute()
            var error: String? = null
            if (response.headers().get("Content-Type")?.contains(
                    "application/json") == true) {
                // Received JSON with an error.
                val json: String? = response.body()?.string()
                error = json?.let {
                    val export = ApiClient.getGson().fromJson(json,
                        ExportPdfResponse::class.java)
                    export.errors?.common?.firstOrNull()
                } ?: getString(R.string.request_error)
            } else {
                // Received PDF.
                val buffer = response.body()?.byteStream()
                if (buffer != null) {
                    val file = context?.let { createFile(it, "pdf") }
                    if (file != null) {
                        copyStreamToFile(buffer, file)
                        launch(Dispatchers.Main) {
                            if (isAdded) {
                                hideProgress(view)
                            }
                        }
                    }
                }
            }
            if (error != null) {
                launch(Dispatchers.Main) {
                    if (isAdded) {
                        hideProgress(view)
                        showErrorDialog(error)
                    }
                }
            }
        } catch (e: Exception) {
            launch(Dispatchers.Main) {
                if (isAdded) {
                    showErrorDialog(getString(R.string.connection_timeout))
                    hideProgress(view)
                }
            }
        }
    }
}

OLD ANSWER

This answer is not applicapable to binary files like PDF. Maybe it can be used with text files.

ApiClient:

val okHttpClient = OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build()

retrofit = Retrofit.Builder()
    .baseUrl(SERVER_URL)
    .client(okHttpClient)
    .addConverterFactory(ScalarsConverterFactory.create()) // It is used to convert Response<String>.
    // .addConverterFactory(GsonConverterFactory.create(gson)) - you can also add this line.
    .build()

Api:

@FormUrlEncoded
@Streaming // You can also comment this line.
@POST("export-pdf/")
suspend fun exportPdf(
    @Field("token") token: String
): Response<String>

Interactor:

private val service by lazy {
    ApiClient.getRetrofit().create(Api::class.java)
}

suspend fun exportPdf(
    token: String
): Response<String> =
    service.exportPdf(token)

Fragment:

private fun exportPdf(token: String) {
    launch {
        try {
            val response = interactor.exportPdf(token)
            var error: String? = null
            if (response.headers().get("Content-Type")?.contains(
                    "application/json") == true) {
                // Received JSON with an error.
                val json: String? = response.body()
                error = json?.let {
                    val export = gson.fromJson(json, ExportPdfResponse::class.java)
                    export.errors?.message?.firstOrNull()
                } ?: getString(R.string.request_error)
            } else {
                // Received PDF.
                val buffer: ByteArrayInputStream? = response.body()?.byteInputStream()
                if (buffer != null) {
                    val file = context?.let { createFile(it, "pdf") }
                    if (file != null) {
                        copyStreamToFile(buffer, file)
                    }
                }
            }
        } catch (e: Exception) {
            launch(Dispatchers.Main) {
                if (isAdded) {
                    showErrorDialog(getString(R.string.connection_timeout))
                }
            }
        }
    }
}

I check response header, then detect if it is JSON or PDF. In case of PDF I use ScalarsConverterFactory to convert response to byte stream. copyStreamToFile copies bytes to a file, I found it in https://stackoverflow.com/a/56074084/2914140.

Instead of 69 857 bytes it created 113 973 bytes file, that is not rendered. I saw inside, it changed all non-latin symbols with other codes.

I tried to write Response<Any> in methods, but it lead to an error: "java.lang.IllegalArgumentException: Unable to create converter for class java.lang.Object for method Api.exportPdf". I tried to write my ConverterFactory for Any, but with no success.

Also changed this code and received errors:

  • java.lang.IllegalStateException: Cannot read raw response body of a converted body.
  • java.lang.IllegalArgumentException: Unable to create converter for class java.lang.String for method Api.exportPdf
  • Unable to create converter for retrofit2.Call for method Api.exportPdf.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!