wrt
wrt

Reputation: 35

Rest Api Post request

I cannot seem to get this to work for me ,I have seen this in other posts and was hoping someone may be able to spot what im doing wrong.I am trying to get the body of a request to this rest api but cannot seem to pull back what i need and just get null in the string below.

@POST
    @Path("/SetFeeds")
    @Consumes(MediaType.APPLICATION_JSON)   
    @Produces(MediaType.APPLICATION_JSON) 
    public String setFeed(@PathParam("name")String name2, @QueryParam("name") String name,@Context UriInfo uriInfo){                
            MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
            String query = uriInfo.getRequestUri().getQuery();
            String response = queryParams.getFirst("name");

            return response;

    } 

Upvotes: 1

Views: 1449

Answers (2)

Andreas Panagiotidis
Andreas Panagiotidis

Reputation: 3002

Great answer, but I would like to add that you can use an object instead of a String and the Jackson of REST will take care the transformation without any further definition.

@POST
@Consumes(MediaType.APPLICATION_JSON)   
@Produces(MediaType.APPLICATION_JSON) 
public String setFeed(@PathParam("name")String name2, 
            @QueryParam("name") String name,
            MyJson json,
            @Context UriInfo uriInfo){                
        MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
        String query = uriInfo.getRequestUri().getQuery();
        String response = queryParams.getFirst("name");

        return response;

and a pojo as a json object:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyJson{

    private String name;

    public MyJson(){}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208944

A method parameter to accept the body of the request should not be annotated with anything (except in few cases like individual form params and multipart). So to get the raw JSON, you could simply add a String parameter

public String setFeed(@PathParam("name")String name2, 
                      @QueryParam("name") String name,
                      @Context UriInfo uriInfo,
                      String jsonBody){

Or if you want to do the more common thing and use POJOs (so you don't need to parse the JSON yourself), you should look at this answer

Upvotes: 5

Related Questions