简体   繁体   中英

How to return XML from a Jersey 400 response code

When a client executes a POST I have to validate the String parameters for bad characters. When I find one I need to return a message to indicate what was incorrect. Normally I use a text/plain, but our customer is using some Oracle tool that must get XML back from a POST request (go figure).

I have created a custom exception to create the response:

public class RESTException extends WebApplicationException {
public RESTException(Response.Status status, String messageKey) {
    super(Response.status(status).entity("a messasge").type(MediaType.TEXT_PLAIN).build());
}
public RESTException(Response.Status status, String messageKey, boolean useEntity) {
    super(Response.status(status).entity(new CDSResponse(Integer.toString(status.getStatusCode()), PropertyFileAccessor.getInstance().getPropertyWithDefault(messageKey))).type(MediaType.APPLICATION_XML).build());
}

Usually I execute the first method above when creating an error, but I crafted the second method with the entity to return the XML.

Here is the method that I use as the endpoing:

@POST
@Consumes({"application/assetId-v1+xml", "application/assetId-v1+json"})
@Produces({MediaType.APPLICATION_XML})
@Path("/{dealerCode}/{dcn}/{make}/{serialNumber}")
public Response postV1(AssetId assetId, @PathParam("dealerCode") String dealerCode, @PathParam("dcn") String dcn, @PathParam("make") String make, @PathParam("serialNumber") String serialNumber) {
    if (!StringUtils.isAlphanumeric(dealerCode)) {
        throw new RESTException(Status.BAD_REQUEST, "equipmentdata.400.invalid.dealer.code", true);
    }

Here is the question/Bug: When I throw a 400, I get this as the response:

cat.dds.cds.model.CDSResponse@29626a

But when I throw any other status code I get xml. What's up?

My solution was simple. Don't send back 400s. In this particular case, the Oracle tool would only accept 200s, so it was not very restful. So everything is a 200 and the response XML had the real code in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM