I saw topics like How to download file in Android using Retrofit library?, they use @Streaming
and RxJava / callbacks.
I have Kotlin, coroutines, Retrofit 2.6.0 and queries like in https://stackoverflow.com/a/56473934/2914140:
@FormUrlEncoded
@Streaming
@POST("export-pdf/")
suspend fun exportPdf(
@Field("token") token: String
): ExportResponse
I have a Retrofit client:
retrofit = Retrofit.Builder()
.baseUrl(SERVER_URL)
.client(okHttpClient)
.build()
service = retrofit.create(Api::class.java)
If a token parameter is right, the query returns PDF file:
%PDF-1.4
%����
...
If it is wrong, it will return JSON with error description:
{
"success": 0,
"errors": {
"message": "..."
}
}
So, ExportResponse is a data class containing JSON fields, POJO.
I cannot access file data with
Response response = restAdapter.apiRequest();
try {
//you can now get your file in the InputStream
InputStream is = response.getBody().in();
} catch (IOException e) {
e.printStackTrace();
}
because ExportResponse is a data class, so val response: ExportResponse = interactor.exportPdf(token)
will return data, not Retrofit object.
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)
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With