[英]Send json part in play-ws multipart request
I'm implementing an external API where I need to send a file attachment bundled with a JSON meta part. 我正在实现一个外部API,我需要发送一个与JSON元件捆绑在一起的文件附件。
The following code is not accepted by the server since Play hardcodes the content type of DataPart
to text/plain
, and the server expects application/json
服务器不接受以下代码,因为Play将
DataPart
的内容类型硬编码为text/plain
,并且服务器需要application/json
val meta = Json.obj(
"name" -> s"Invoice ${invoiceNumber}.pdf",
"referenceType" -> "INVOICE",
"referenceId" -> 42
)
ws.url("{API-URL}")
.addHttpHeaders("Authorization" -> s"Bearer ${accessToken}")
.post(Source(DataPart("meta", meta.toString) :: FilePart("file", s"Invoice ${invoiceNumber}.pdf", Option("application/pdf"), FileIO.fromPath(file.toPath)) :: List()))
.map(res => {
logger.debug("Status: " + res.status)
logger.debug("JSON: " + res.json)
Right(invoiceNumber)
})
The example curl (that I've tested and verified) command for the API endpoint is: API端点的示例curl(我已经过测试和验证)命令是:
curl -H "Authorization: Bearer {accessToken}" \
-F 'meta={"name": "Invoive 4.pdf", "referenceType": "INVOICE", "referenceId": 42 } \
;type=application/json' \
-F "file=@Invoice.pdf" \
'{API-URL}'
Is there a simple way to either force DataPart
to use a different content-type or use a different Part to get more control over what I'm sending? 是否有一种简单的方法可以强制
DataPart
使用不同的内容类型,还是使用不同的Part来更好地控制我发送的内容?
I found a solution to the issue: 我找到了解决问题的方法:
First I create a temporary file to hold the meta data 首先,我创建一个临时文件来保存元数据
val meta = new File(s"/tmp/${UUID.randomUUID()}")
Files.write(meta.toPath, Json.obj(
"name" -> s"Invoice ${invoiceNumber}.pdf",
"referenceType" -> "INVOICE",
"referenceId" -> 42
).toString.getBytes)
I then use two FilePart
's in my request: 然后我在我的请求中使用了两个
FilePart
:
ws.url("{API-URL}")
.addHttpHeaders("Authorization" -> s"Bearer ${accessToken}")
.post(Source(FilePart("meta", "", Option("application/json"), FileIO.fromPath(meta.toPath)) :: FilePart("file", s"Invoice ${invoiceNumber}.pdf", Option("application/pdf"), FileIO.fromPath(file.toPath)) :: List()))
.map(res => {
logger.debug("Status: " + res.status)
logger.debug("JSON: " + res.json)
Right(invoiceNumber)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.