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

血红的双手。 提交于 2021-02-16 06:17:06

问题


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

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

I've created a POST processing method as follows:

@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.

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


回答1:


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

@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.




回答2:


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 HttpServletRequest to be empty by the time it reaches the RequestMapping. Adding the FilterRegistrationBean Bean solves that issue.



来源:https://stackoverflow.com/questions/36901714/how-to-get-raw-binary-data-from-a-post-request-processed-by-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!