改造 2 多部分请求
Retrofit 2 Multipart requests
我正在将我现有的代码库迁移到 Retrofit 2,但在理解 Multipart 请求的新语法时遇到一些问题。我也在使用 Kotlin,尽管除了一些语法更改外,我认为对于这个特定问题应该无关紧要。
这是我现在拥有的:
val audioDuration = RequestBody.create(null, audioDuration.toString())
val file = RequestBody.create(MediaType.parse("audio/mp4"),
File(context.filesDir, filename).absoluteFile)
sendAudioChunk(audioDuration, file).enqueue(callback)
这里是 API 的定义:
@Multipart
@POST("path_to_request")
fun sendAudioChunk(@Part("duration") audioDuration: RequestBody,
@Part("audio") audioBlob: RequestBody) : Call<ResponseObject>
在 Retrofit 1.9 上,我使用 TypedString 和 TypedFile 作为请求参数,现在看来需要使用 OkHttp 的 RequestBody,但我一定是遗漏了一些东西,因为请求没有正确执行。
有一点不同的是,TypedString
的 Content-Type
为 "text/plain; charset=UTF-8",而您根本没有为 [=14] 设置 Context-Type
=] 参数。尝试将其设置为 text/plain
以获得与 TypedString
相同的行为(字符集默认设置为 utf-8)。
val audioDuration = RequestBody.create(MediaType.parse("text/plain"), audioDuration.toString())
如果这不起作用,您需要提供更多有关 "request does not execute correctly" 的信息。您尝试复制的工作请求也会有所帮助。
我终于明白了。我的网络服务需要一个文件名来上传文件。这似乎是新 Retrofit 2 中正在进行的支持工作,但可以通过将其添加到命名参数定义来规避该问题。
我正在将我现有的代码库迁移到 Retrofit 2,但在理解 Multipart 请求的新语法时遇到一些问题。我也在使用 Kotlin,尽管除了一些语法更改外,我认为对于这个特定问题应该无关紧要。
这是我现在拥有的:
val audioDuration = RequestBody.create(null, audioDuration.toString())
val file = RequestBody.create(MediaType.parse("audio/mp4"),
File(context.filesDir, filename).absoluteFile)
sendAudioChunk(audioDuration, file).enqueue(callback)
这里是 API 的定义:
@Multipart
@POST("path_to_request")
fun sendAudioChunk(@Part("duration") audioDuration: RequestBody,
@Part("audio") audioBlob: RequestBody) : Call<ResponseObject>
在 Retrofit 1.9 上,我使用 TypedString 和 TypedFile 作为请求参数,现在看来需要使用 OkHttp 的 RequestBody,但我一定是遗漏了一些东西,因为请求没有正确执行。
有一点不同的是,TypedString
的 Content-Type
为 "text/plain; charset=UTF-8",而您根本没有为 [=14] 设置 Context-Type
=] 参数。尝试将其设置为 text/plain
以获得与 TypedString
相同的行为(字符集默认设置为 utf-8)。
val audioDuration = RequestBody.create(MediaType.parse("text/plain"), audioDuration.toString())
如果这不起作用,您需要提供更多有关 "request does not execute correctly" 的信息。您尝试复制的工作请求也会有所帮助。
我终于明白了。我的网络服务需要一个文件名来上传文件。这似乎是新 Retrofit 2 中正在进行的支持工作,但可以通过将其添加到命名参数定义来规避该问题。