如何在Play中发送multipart / related请求

时间:2015-08-31 18:12:08

标签: scala http tesseract playframework-2.3 multipart

我正在将我的scala 2.11.6,playframework 2.3.8与open-ocr(tesseract)集成,它需要发送多部分/相关数据。

我正在尝试这样做,手动生成多部分请求

        val postBody = s"""--separator--
                |Content-Type: application/json;
                |
                | { "engine": "tesseract" }
                |
                |--separator--
                | Content-Type: image/png;
                |
                | ${Base64.getEncoder().encodeToString(image)}
                |--separator--
            """.stripMargin
        val parseResult = WS.
            url("http://127.0.0.1:9292/ocr-file-upload").
            withMethod("POST").
            withHeaders(
                "Content-Type" -> "multipart/related",
                "boundary" -> "separator").
            withBody(postBody).
            execute()

但它不起作用。 Open-ocr无法读取请求标头。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我使用的解决方案是使用ning Multipart响应生成器手动生成body。

旧版 1.8.0

{
"resname": "Sankalp",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "25"
}
{
"resname": "South Cafe",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "20"
}
{
"resname": "Uncle Sam",
"restadd": "Infocity",
"resttime": "Pizza",
"images": "15"
}
{
"resname": "Dangee Dums",
"restadd": "Infocity",
"resttime": "Dessert",
"images": "10"
}
{
"resname": "Fresh Roast",
"restadd": "Infocity",
"resttime": "Cafe",
"images": "5"
}

最新版本 1.9.31

import com.ning.http.client.FluentCaseInsensitiveStringsMap
import com.ning.http.client.multipart._

...

    // Step 1. Generating tesseract json configuration
    val json = new StringPart("config", """{ "engine": "tesseract" }""", "utf-8")
    json.setContentType("application/json")
    // Step 2. Generating file part
    val filePart = new FilePart("file", new ByteArrayPartSource("image.png", image), "image/png", null)
    // Step 3. Build up the Multiparts
    val reqE = new MultipartRequestEntity(
        Array(filePart, json),
        new FluentCaseInsensitiveStringsMap().add("Content-Type", "multipart/related")
    )
    // Step 3.1. Streaming result to byte array
    val bos = new ByteArrayOutputStream()
    reqE.writeRequest(bos)
    // Step 4. Performing WS request upload request
    val parseResult = WS
        .url("http://127.0.0.1:9292/ocr-file-upload")
        .withHeaders("Content-Type" -> reqE.getContentType()).
        post(bos.toByteArray());
    // Step 5. Mapping result to parseResult
    parseResult.map(_.body)
相关问题