Java – Unsupported Media Type – HTTP Status 415

Unsupported Media Type – HTTP Status 415… here is a solution to the problem.

Unsupported Media Type – HTTP Status 415

I have a problem with my network service.
The GET request performs well and correctly, but the post request gets HTTP status 415.

The project I’m working on is a JAX-RS RESTful API that needs to communicate with an Android mobile app. I can receive information from GET statements.

Here is the code for my LoginFormat object:

@XmlRootElement
public class LoginFormat {

private String username;
    private String password;

public String getUsername() {
        return username;
    }

public void setUsername(String username) {
        this.username = username;
    }

public String getPassword() {
        return password;
    }

public void setPassword(String password) {
        this.password = password;
    }
}

Here you can see an example of the POST of my CoCreationService class:

@Path("/User")
public class CoCreationService {
    @POST
    @Path("/testLogin") 
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response parseTerm(LoginFormat login) {  

return Response.status(200).entity(login.getUsername() + login.getPassword()).build();  
    }
}

I

tried so much that I was confused about it.

I’m using curl to test the web service:

curl -i -X POST -H 'Content-Type: application/json' -d '{"username": "testuser", "password": "test"}' http://localhost:8080/CoCreationService/api/User/testLogin

Are there some settings that need clarification, or am I making a serious mistake?

PS: I’m using NetBeans.

EDIT: POST! with text/plain text

@POST
@Path("/testPost")
@Consumes("text/plain")
public Response postClichedMessage(String message) {       
    return Response.status(200).entity(message).build();
}

Solution

There is no problem with the code. The only thing you need to do is include the appropriate library in your classpath that knows how to decode JSON strings. If you use Maven, you can simply add another dependency:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey.version}</version>
</dependency>

As long as you are using Netbeans, you can see something like this in the AS logs:

SEVERE: A message body reader for Java class LoginFormat, and 
Java type class LoginFormat, and MIME media type application/json 
was not found.

The registered message body readers compatible with the MIME media type are:

Related Problems and Solutions