繁体   English   中英

在play-ws multipart请求中发送json部分

[英]Send json part in play-ws multipart request

我正在实现一个外部API,我需要发送一个与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)
  })

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}'

是否有一种简单的方法可以强制DataPart使用不同的内容类型,还是使用不同的Part来更好地控制我发送的内容?

我找到了解决问题的方法:

首先,我创建一个临时文件来保存元数据

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)

然后我在我的请求中使用了两个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM