Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST JSON request to a Jersey REST service?

I can successfully post XML data to my service, but, trying to do the same using JSON is failing. The POJO is:

@XmlRootElement
public class Address {
    String city;
    String zip;
    //Getters & setters...
}

The service resource is:

@POST
@Produces("application/json")
public Address fix(Address a) {
    return a;
}

I am doing a POST as follows:

POST /AcmeWeb/svc/simple HTTP/1.1
Content-Length: 30
Content-Type: application/json; charset=UTF-8

{"city":"Miami","zip":"33130"}

The server is responding with a 400 Bad Request. I scoured the Internet but found no good example of posting JSON. Any help is appreciated. Thanks.

like image 597
RajV Avatar asked Mar 15 '12 15:03

RajV


1 Answers

Add @Consumes("application/json") annotation to your fix() method.

Update: This works for me:

Resource method:

@POST
@Produces("application/json")
@Consumes("application/json")
public Address post(Address addr) {
    return addr;
}

Address class:

@XmlRootElement
public class Address {
    public String city;
    public String zip;
}

This is the request I am sending:

Accept  application/json
Content-Type    application/json; charset=UTF-8

{"city":"Miami","zip":"33130"}

This is what I get as a response:

{"city":"Miami","zip":"33130"}
like image 114
Martin Matula Avatar answered Sep 20 '22 07:09

Martin Matula