简体   繁体   中英

HTTP/1.1 415 Unsupported Media Type while processing JSON

My code is working with Xml but fails with Json

Request with RestEasy UI:

POST /api/people HTTP/1.1
Content-Type:application/json

{
    "name":"developer",
    "age":"25",
    "address":"address"
}

Class Resource.java

package people;

@Path("/api")
public class Resource {

    @GET
    @Produces("text/plain")
    @Path("helloworld")
    public String helloWorld() {
        return "Hello World!";
    }

    @POST
    @Produces("text/plain")
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("people")
    public String updatePeople(People request)  { 
        People p = new People();
        p.setName(request.getName());

        return p.getName(); 
    }
}

and class People.java

package people;

@XmlRootElement
public class People {

    private String name;
    private String age;
    private String address;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

}

add default constructor in bean class People.

 public people(){
   }

Add the following jar to your class path. jersey-media-json-jackson.jar

If you are using Maven, add this to your POM.xml file.

<dependency>
   <groupId>org.glassfish.jersey.media</groupId>
   <artifactId>jersey-media-json-jackson</artifactId>
   <version>2.27</version>
</dependency>

Probably you are facing the following exception on the server side:

javax.ws.rs.NotSupportedException: RESTEASY003200: Could not find message body reader for type: class people.People of content type: application/json

In this case you need to add the resteasy-jackson2-provider dependency to your project ; so, assuming that you are using Maven, try putting this into your pom.xml :

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.6.0.Final</version>
</dependency>

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