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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…