【问题标题】:How to return binary data from SoapUI REST mock如何从 SoapUI REST 模拟返回二进制数据
【发布时间】:2021-12-21 16:27:36
【问题描述】:

我正在尝试创建一个从文件中读取二进制数据的 REST 模拟服务。模拟服务需要仅使用二进制数据作为内容发送回 HTTP 响应。我不知道二进制数据的编码。我搜索了可能的解决方案,但找不到任何解决方案。谁能帮我解决这个问题?

到目前为止,我尝试将文件中的字节填充到响应字符串中,但使用 Postman 分析时数据似乎已损坏。在下面的示例中,我使用 PDF 文件作为输入。代码在 MockResponse 中作为脚本运行。

def file = new java.io.File("D:/tmp/test.pdf")
byte[] fileBytes = file.getBytes()
String fileString = new String(fileBytes)
mockResponse.setResponseContent(fileString)

我在 Windows 10 上运行 SoapUI 5.6.0。

【问题讨论】:

    标签: soapui


    【解决方案1】:

    经过一些研究,我发现可以将数据从文件流式传输到 httpResponse。以下代码按要求工作:

    import org.apache.commons.io.IOUtils
    
    def httpResponse = mockRequest.httpResponse
    def file = new java.io.File("D:/tmp/test.pdf")
    
    // Set Header values as needed
    mockRequest.httpResponse.addHeader("Content-Type", "application/octet-stream")
    mockRequest.httpResponse.addHeader("Content-Disposition", "attachment;filename=test.pdf")
    
    try {
    
      FileInputStream fis = new FileInputStream(file);
      OutputStream os = httpResponse.getOutputStream()
    
      IOUtils.copy(fis,os)
    
    } catch (Exception e){
      log.info " error"
    }
    finally {
      fis.close()
      os.close()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多