为什么Resonse.ok()。build()返回Response实体本身?


问题内容

我有一个简单的REST API,我只返回了Resonse.ok()。build(),因为该函数的主体是异步的

我原本以为200状态代码的响应是空的,但是我却获得了对似乎是实体的Response调用的完整描述。

我做错什么了?

这是我从API调用收到的json响应

{
    "context": {
        "headers": {},
        "entity": null,
        "entityType": null,
        "entityAnnotations": [],
        "entityStream": {
            "committed": false,
            "closed": false
        },
        "length": -1,
        "language": null,
        "location": null,
        "committed": false,
        "mediaType": null,
        "allowedMethods": [],
        "links": [],
        "entityTag": null,
        "stringHeaders": {},
        "lastModified": null,
        "date": null,
        "acceptableMediaTypes": [
            {
                "type": "*",
                "subtype": "*",
                "parameters": {},
                "quality": 1000,
                "wildcardType": true,
                "wildcardSubtype": true
            }
        ],
        "acceptableLanguages": [
            "*"
        ],
        "entityClass": null,
        "responseCookies": {},
        "requestCookies": {},
        "lengthLong": -1
    },
    "status": 200,
    "length": -1,
    "language": null,
    "location": null,
    "metadata": {},
    "cookies": {},
    "mediaType": null,
    "allowedMethods": [],
    "links": [],
    "statusInfo": "OK",
    "entityTag": null,
    "stringHeaders": {},
    "entity": null,
    "lastModified": null,
    "date": null,
    "headers": {}
}

REST API看起来像这样

@RestController
@RequestMapping("/accountworkers")
@Api(value = "/updater")
public class AccountUpdater {

    private static Logger LOGGER = LoggerFactory.getLogger(AccountUpdater.class);

    @Autowired
    private AccountUpdaterController auController;

    @RequestMapping(value = "/updater", method = RequestMethod.GET)
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response runUpdater() {
        LOGGER.info("Running account updater");
        auController.doAccountUpdateAsync();
        return Response.ok().build();
    }
}

问题答案:

您正在尝试混合使用JAX-RS和Spring MVC。这些不是同一件事,并且不兼容。通过返回ResponseSpring
MVC无法识别的,它像对待其他实体一样对它进行序列化。如果您正在使用Spring
MVC,那么您想使用ResponseEntity

return ResponseEntity.ok().build()

如果您使用的是Spring MVC,则应该删除Jersey / JAX-RS的所有依赖项,以免使您对可以使用和不能使用的内容感到困惑。

另外,@ProducesJAX-RS也适用。对于Spring
MVC,应该将农产品添加到@RequestMapping注释内。

@RequestMapping(value="/", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)