2015-08-31 86 views
1

我正在將我的Scala 2.11.6,playframework 2.3.8與open-ocr(tesseract)集成在一起,它需要發送多部分/相關數據。如何在Play中發送多部分/相關請求

我試圖做到這一點,手動生成多要求

 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無法讀取請求的標題。

我該怎麼做?

+0

什麼不起作用?你能更精確嗎? – MirMasej

+0

對不起我的壞。 Open-ocr無法讀取請求的標題 – mavarazy

回答

0

我使用的解決方案是使用ning Multipart響應生成器手動生成身體。

隨着老版1.8.0

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) 

隨着最新版本31年9月1日

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" }""", "application/json", Charset.forName("utf-8")) 
    // Step 2. Generating file part 
    val filePart = new ByteArrayPart("image.png", scaledImage, "image/png") 
    // Step 3. Build up the Multiparts 
    val reqE = MultipartUtils.newMultipartBody(
     util.Arrays.asList(filePart, json), 
     new FluentCaseInsensitiveStringsMap().add("Content-Type", "multipart/related") 
    ) 
    // Step 3.1. Streaming result to byte array 
    val bos = ByteBuffer.allocate(scaledImage.length + 1024) 
    reqE.read(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.array()); 
    // Step 5. Mapping result to parseResult 
    parseResult.map(_.body) 
相關問題