为什么spring-data-rest中的allps(或profile)路径返回的json body的头部Content-Type: texthtml不匹配?

问题描述 投票:6回答:1

现在,我的spring-data-rest的默认Content-Type (spring-boot 1.4.3.RELEASE),但控制器是 application/hal+json 这是有道理的。 如果我使用chrome,我得到的是 application/hal+json 为我的应用程序的根,例如,因为chrome使用的接受头是 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8". 然而, /profile (正式 /alps)即使响应体是json,URL也会提供texthtml(使得Content-Type与body不匹配)。 如果你特别要求只有applicationjson,那么你就会得到正确的响应头。

这里是不正确的工作情况(当返回的文档体不是texthtml时,返回texthtml)。

$ http --verbose "http://localhost:8080/v1/profile/eldEvents" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"

GET /v1/profile/eldEvents HTTP/1.1
Accept:  text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8080
User-Agent: HTTPie/0.9.2



HTTP/1.1 200 
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Location, X-Auth, Authorization
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Location
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html;charset=UTF-8
Date: Fri, 03 Feb 2017 01:16:14 GMT
Expires: 0
Pragma: no-cache
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
Transfer-Encoding: chunked
X-Application-Context: application
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

{
  "alps" : {
    "version" : "1.0",
    "descriptors" : [ {
      "id" : "eldEvent-representation",
      "href" : "http://localhost:8080/v1/profile/eldEvents",
      "descriptors" : [ {
        "name" : "sequenceId",
        "type" : "SEMANTIC"
      }, {
...

切掉响应的其他部分,从上面你可以看到它是json数据。

我相信上述请求的正确Content-Type应该是类似于 "applicationjson "的东西。

spring-data-rest
1个回答
0
投票

如果这对你来说还是相关的。我已经解决了这个问题,通过手动覆盖所有对你的请求。/profile/* 没有 content-type 定义。

@Component
public class ProfileContentTypeFilter extends OncePerRequestFilter
{
    private static final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException
    {
        if (request.getContentType() == null && matcher.match("/profile/*", request.getRequestURI()))
        {
            // Override response content type for unspecified requests on profile endpoints
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        }

        filterChain.doFilter(request, response);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.