我看到了像How to download file in Android using Retrofit library?这样的主题,它们使用了@Streaming和RxJava/回调。

我有Kotlin,协程,Retrofit 2.6.0和类似https://stackoverflow.com/a/56473934/2914140的查询:

@FormUrlEncoded
@Streaming
@POST("export-pdf/")
suspend fun exportPdf(
    @Field("token") token: String
): ExportResponse

我有一个改造客户:
retrofit = Retrofit.Builder()
    .baseUrl(SERVER_URL)
    .client(okHttpClient)
    .build()

service = retrofit.create(Api::class.java)

如果 token 参数正确,查询将返回PDF文件:
%PDF-1.4
%����
...

如果错误,它将返回带有错误描述的JSON:
{
    "success": 0,
    "errors": {
        "message": "..."
    }
}

因此,ExportResponse是一个包含JSON字段POJO的数据类。

我无法使用
Response response = restAdapter.apiRequest();

try {
    //you can now get your file in the InputStream
    InputStream is = response.getBody().in();
} catch (IOException e) {
    e.printStackTrace();
}

因为ExportResponse是数据类,所以val response: ExportResponse = interactor.exportPdf(token)将返回数据,而不是Retrofit对象。

最佳答案

您可以将exportPdf的返回类型更改为Call<ResponseBody>,然后检查响应代码。如果可以,请以流的形式读取正文。如果不是,请尝试反序列化ExportResponse。
我猜它看起来像这样:

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
}

更新

这是我的测试的完整 list :
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>
}

这是用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')

一切对我都很好

更新2

看来您必须在Api中编写以下代码:
@FormUrlEncoded
@Streaming // You can also comment this line.
@POST("export-pdf/")
fun exportPdf(
    @Field("token") token: String
): Call<ResponseBody>

09-26 09:03