如何构建一个没有身体的POST请求

abo*_*ger 6 post http spring-data-rest spring-boot

我有一个HTTP客户端向POST服务器发送许多请求.服务器响应所有请求201 Created和响应正文.就我的目的而言,响应标题就足够了,因为我只对Location标题感兴趣.我想避免服务器生成响应主体以显着减少网络流量.

根据RFC 7231,...

  [...] if one or more resources has been created on the origin server as a
  result of successfully processing a POST request, the origin server
  SHOULD send a 201 (Created) response containing a Location header [...]
Run Code Online (Sandbox Code Playgroud)

...,因此,我认为,服务器也可以回复例如204 No Content,省略身体.

因此我的问题是:是否有可能构建一个POST使服务器响应204 No Content或以另一种方式省略响应体的请求?

更新1:服务器端是一个Spring Data REST项目,我可以自由配置它.我知道我可以设置RepositoryRestConfiguration#setReturnBodyOnCreatefalse,但它会影响所有传入的请求,这将是过头了.因此,我更愿意在客户端做出决定.

abo*_*ger 0

根据 Evert 和 Bertrand 的答案加上一些谷歌搜索,我最终在 Spring Data REST 服务器中实现了以下拦截器:

@Configuration
class RepositoryConfiguration {

    @Bean
    public MappedInterceptor preferReturnMinimalMappedInterceptor() {
        return new MappedInterceptor(new String[]{"/**"}, new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                if ("return=minimal".equals(request.getHeader("prefer"))) {
                    response.setContentLength(0);
                    response.addHeader("Preference-Applied", "return=minimal"");
                }
                return true;
            }
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

它产生以下通信,这对于我的目的来说已经足够了:

> POST /versions HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.59.0
> Accept: */*
> Content-Type: application/json
> Prefer: return=minimal
> Content-Length: 123
>
> [123 bytes data]

...

< HTTP/1.1 201
< Preference-Applied: return=minimal
< ETag: "0"
< Last-Modified: Fri, 30 Nov 2018 12:37:57 GMT
< Location: http://localhost:8080/versions/1
< Content-Type: application/hal+json;charset=UTF-8
< Content-Length: 0
< Date: Fri, 30 Nov 2018 12:37:57 GMT
Run Code Online (Sandbox Code Playgroud)

我想平均分享赏金,但这是不可能的。它归于 Bertrand,因为他给出的答案指导了我的实施。感谢您的帮助。