向Spring MVC发送二进制数据失败,出现“内容类型”application/octet-stream;字符集=UTF-8'不支持”

ymdaylpp  于 2022-11-15  发布在  Spring
关注(0)|答案(3)|浏览(519)

我想发送二进制数据到Spring MVC中的POST方法。不需要多部分表单数据,因为不需要额外的信息。

@PostMapping(value = "/post", consumes = "application/octet-stream")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void post(final RequestEntity<InputStream> entity) {
    // final InputStream is = entity.getBody(); // process content
}

出于测试目的,使用cURL发送数据:

curl --header "Content-Type:application/octet-stream" --data-binary @pom.xml http://localhost:8080/post

但是每个请求都失败,HTTP状态为415:

{
    "timestamp": "2020-01-22T08:27:28.063+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream;charset=UTF-8' not supported",
    "path":"/post"
}

如何让它发挥作用?

sycxhyv7

sycxhyv71#

问题出在post方法的RequestEntity参数上。
只需使用HttpServletRequest作为参数。

@PostMapping(value = "/post", consumes = "application/octet-stream")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void post(final HttpServletRequest request) {
    // final InputStream is = request.getInputStream(); // process content
}
c6ubokkw

c6ubokkw2#

@PostMapping(value="/uploadBinary", consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
    public ResponseEntity<?> getBinary(HttpEntity<String> reqEntity) {
        System.out.println(reqEntity.getHeaders());
        System.out.println(reqEntity.getBody());
        byte[] arr;
        try {
            arr = reqEntity.getBody().getBytes();
            for(byte b: arr){
                System.out.println(String.format("%02X", b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

上面的代码和下面的命令对我很有效:

echo -en '\x03\x04' | curl -X POST  --header "Content-Type:application/octet-stream" --data-binary @-  https://localhost:8080/uploadBinary

或者,可以在控制器端使用以下代码:

@PostMapping(value = "/uploadBinary", consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
    public ResponseEntity<?> getBinary(@RequestBody byte[] body) {
        for (byte b : body) {
            System.out.println(String.format("%02X", b));
        }
        return new ResponseEntity<>(HttpStatus.OK);
}
dsf9zpds

dsf9zpds3#

上述代码在内容类型为application/octet-stream的情况下运行良好

相关问题