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

JonathanReez picture JonathanReez · Apr 28, 2016 · Viewed 19.9k times · Source

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?

Answer

nimai picture nimai · Feb 7, 2018

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.