问题
I have a simple REST API for which I am just returning Resonse.ok().build(), since the body of the function is asynchronous
I was expecting an empty response with a 200 http status code, but instead I got a full description of what seems to be the Response calls as entity.
What did I do wrong?
Here is the json response that I received from my API call
{
"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": {}
}
the REST api looks like this
@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();
}
}
回答1:
You are trying to mix JAX-RS and Spring MVC. These are not the same thing and are not compatible. By returning Response
, which Spring MVC doesn't recognize, it it serializing it like it would any other entity. If you are using Spring MVC, then you want to be using ResponseEntity.
return ResponseEntity.ok().build()
If you are using Spring MVC, you should remove any dependencies for Jersey/JAX-RS so you don't get confused as to what you can and cannot use.
Aside, @Produces
is also for JAX-RS. For Spring MVC, you are supposed to add the produces inside the @RequestMapping annotation.
@RequestMapping(value="/", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
来源:https://stackoverflow.com/questions/51548134/why-resonse-ok-build-return-the-response-entity-itself