【问题标题】:How to get raw binary data from a POST request processed by Spring?如何从 Spring 处理的 POST 请求中获取原始二进制数据?
【发布时间】:2016-08-22 10:52:29
【问题描述】:

我需要编写一个能够处理CUrl发送的二进制数据的应用程序,例如:

curl localhost:8080/data --data-binary @ZYSF15A46K1.txt

我创建了一个POST处理方法如下:

@RequestMapping(method = RequestMethod.POST, value = "/data")
    public void acceptData(HttpEntity<byte[]> requestEntity) throws Exception {
        process(requestEntity.getBody());
    }

但它似乎没有返回原始二进制数据。我尝试发送一个 GZip 文件,在经过 Spring 之后,它现在可以更长时间地解压缩,这让我相信我得到的数据要么太多,要么太少。

如何解决此问题并获取原始二进制数据?

【问题讨论】:

  • 尝试使用HttpServletDequest作为控制器的输入参数,并从InputStream读取原始数据。
  • @GeminiKeith 也尝试过,由于某种原因它总是返回一个空对象。
  • 你设置过字符编码吗?您可以查看Content-Length 以确保您收到正确的请求。如果Content-Length 有效,则可以从InputStream 中读取指定长度。如果不是,请检查您的请求。
  • @GeminiKeith 谢谢!我对 HttpServletRequest 进行了更多研究,问题已解决(请参阅我的答案)。

标签: java spring curl binary-data


【解决方案1】:

我能够使用以下代码解决此问题:

@Bean
public FilterRegistrationBean registration(HiddenHttpMethodFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(false);
    return registration;
}

@RequestMapping(method = RequestMethod.POST, value = "/data")
public void acceptData(HttpServletRequest requestEntity) throws Exception {
    byte[] processedText = IOUtils.toByteArray(requestEntity.getInputStream());
    processText(processedText);
}

Spring 默认进行预处理,这会导致HttpServletRequest 在到达RequestMapping 时为空。添加FilterRegistrationBean Bean 解决了这个问题。

【讨论】:

  • 是的,我忘记了。输入流默认只能读取一次。
  • 我的直觉是时髦的 HiddenHttpMethodFilter 禁用是关闭自动多部分过滤:stackoverflow.com/a/32790327/32453
【解决方案2】:

就像在控制器方法的参数中声明 InputStream 一样简单:

@RequestMapping(method = RequestMethod.POST, value = "/data")
public void acceptData(InputStream dataStream) throws Exception {
    processText(dataStream);
}

您不需要禁用 HiddenHttpMethodFilter,如果您这样做,可能是您的请求在某些方面是错误的。见https://github.com/spring-projects/spring-boot/issues/5676

【讨论】:

  • "wrong in some way" = 检查请求中是否设置了Content-Type 标头,并且它不是multipart/form-dataapplication/x-www-form-url-encoded
  • 我应该使用什么注释来从 postman 获取二进制数据到 spring boot?
  • 这取决于您如何使用邮递员发送。请参阅此learning.getpostman.com/docs/postman/sending-api-requests/…。如果您发送“原始”数据,则可以按原样使用上述声明。
猜你喜欢
  • 2019-08-15
  • 2018-02-05
  • 2011-04-28
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
相关资源
最近更新 更多