java 如何从 Spring 处理的 POST 请求中获取原始二进制数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36901714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:59:28  来源:igfitidea点击:

How to get raw binary data from a POST request processed by Spring?

javaspringcurlbinary-data

提问by JonathanReez

I need to write an application which would be able to process binary data sent by CUrl, such as:

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

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

I've created a POST processing method as follows:

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

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

However it doesn't seem to be returning raw binary data. I've tried sending a GZip file and after going through Spring it is now longer decompressible, which leads me to believe I'm either getting too much data or too little data.

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

How do I solve this issue and get raw binary data?

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

回答by nimai

It's as easy as declaring an InputStream in your controller method's parameters:

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

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

You shouldn't need to disable HiddenHttpMethodFilter, if you do it's probably that your request is wrong in some way. See https://github.com/spring-projects/spring-boot/issues/5676.

您不需要禁用 HiddenHttpMethodFilter,如果您这样做,可能是您的请求在某种程度上是错误的。请参阅https://github.com/spring-projects/spring-boot/issues/5676

回答by JonathanReez

I was able to resolve this using the following code:

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

@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 does pre-processing by default, which causes the HttpServletRequestto be empty by the time it reaches the RequestMapping. Adding the FilterRegistrationBeanBean solves that issue.

Spring 默认会进行预处理,这会导致HttpServletRequest当它到达RequestMapping. 添加FilterRegistrationBeanBean 解决了这个问题。