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

时间:2019-03-28 09:45:20

标签: scala playframework play-ws

我正在实现一个外部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来更好地控制我发送的内容?

1 个答案:

答案 0 :(得分:0)

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

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

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