简体   繁体   中英

How to parse request body of POST request, if client set content-type="application/xml" and body=null?

I have POST REST endpoint, which initially doesn't expect any request body. I want to add optional request body for this API. Optional, means I want all clients, which used this API with content-type="application/xml" and empty body, to continue using API in the same manner, without rewriting any single row of code. For content-type="application/json", it works fine, no need client to alter his code. But for "application/xml", clients now receive "400 Bad request" response. Is there any chance to introduce optional request body and support all existing API clients?

REST endpoint is written in java, and annotations from "javax.xml.bind.annotation" package are used to declare object model

Below is signature of endpoint, defined with swagger annotations. dueDatesDetails - object that is supposed to be added as optional:

@POST
@Path("/sites/{siteid}/filestatus")
public Response linkContent(
        @ApiParam(value = "site id", required = true) @PathParam("siteid") String siteId,
        @ApiParam(value = "status", required = true) @QueryParam("status") String status,
        DueDatesDetails dueDatesDetails) {

Here is java object model, that must be optional:

@XmlRootElement(name = "duedatesdetails")
@XmlAccessorType(XmlAccessType.FIELD)
public class DueDatesDetails
{
    @Getter
    @Setter
    @XmlElement(name = "duedatedetails")
    @JsonProperty("duedatesdetails")
    private List<DueDateDetails> dueDateDetailsList;
}

You can't use request body as a method parameter then. I believe the framework you are using (most likely Spring) doesn't have optional request body feature. You have to manually get the payload from request stream & process it. It should be something like:

@POST
@Path("/sites/{siteid}/filestatus")
public Response linkContent(
        @ApiParam(value = "site id", required = true) @PathParam("siteid") String siteId,
        @ApiParam(value = "status", required = true) @QueryParam("status") String status, HttpServletRequest request) {
        byte[] payload = IOUtils.toByteArray(request.getReader(), request.getCharacterEncoding());      
        String body =  new String(payload, request.getCharacterEncoding());
        if(body == null){
            // do something
        } else {
            // parse body to convert to xml object dueDatesDetails
        }

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