SEMP
SEMP

Reputation: 21

Error 415 on POST with jersey

When I use POST on the client side, I receive the following error.

HTTP Status 415 - Unsupported Media Type
Type: Status Report
Message: Unsupported Media Type
Description: The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.

I've been trying to fix the problem following many posts. I hope I haven't used incompatible solutions.

The GET part works fine, and I'm using Gson to convert to JSON.

Originally my code didn't extend from Application, but it was part of a solution in another post where they registered the Jackson for JSON support.

This is the code for my Service Class:

package com.tutorialspoint;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.google.gson.Gson;

@Path("/UserService")

public class UserService extends Application
{
    UserDao userDao = new UserDao();

    @Override
    public Set<Class<?>> getClasses()
    {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(JacksonFeature.class);

        return classes;
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers()
    {
        List<User> userList = userDao.getAllUsers();
        Response.Status responseStatus = Response.Status.ACCEPTED;

        return getJSONResponse(responseStatus, userList);
    }

    @POST
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser
    (
            @FormParam("id") int id,
            @FormParam("name") String name,
            @FormParam("profession") String profession,
            @Context HttpServletResponse servletResponse) throws IOException
    {
        User user = new User(id, name, profession);

        boolean userAdded = userDao.addUser(user);

        if(userAdded)
        {
            return getJSONResponse(Status.CREATED, id);
        }

        //Should be changed to an error response later.
        return getJSONResponse(Status.CREATED, id);
    }

    public static Response getJSONResponse(Response.Status status, Object entity)
    {
        String json = new Gson().toJson(entity);

        return Response.status(status).entity(json).header("Access-Control-Allow-Origin", "*").build();
    }
}

This is the request made by the client. It was captured using nc command from linux on the cient computer.

POST /UserManagement/rest/UserService/users HTTP/1.1
Host: localhost:58585
Connection: keep-alive
Content-Length: 47
Accept: application/json
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
content-type: text/plain
Referer: http://localhost:4200/persons
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

{"id":1,"name":"Mahesh","profession":"Teacher"}

thanks in advance.


EDIT 01

So you need to send header with name Content-type and value application/json instead of text/plain

I sent the request with content-type: application/json as suggested by @user7294900. (I couldn't send it correctly through my client in Angular 2, so I used telnet instead)

POST /UserManagement/rest/UserService/users HTTP/1.1
Host: localhost:58585
Connection: keep-alive
Content-Length: 47
Accept: application/json
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
content-type: application/json
Referer: http://localhost:4200/persons
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

{"id":1,"name":"Mahesh","profession":"Teacher"}

After that I got Error 500 as stated by @braunpet

You want your client to send JSON but the backend expects an HTML form (@FormParam), which is sent as media type application/x-www-form-urlencoded.

After that I changed my Service class like this (using User as parameter for createUser):

package com.tutorialspoint;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
//import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
//import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.google.gson.Gson;

@Path("/UserService")

public class UserService extends Application
{
    UserDao userDao = new UserDao();

    @Override
    public Set<Class<?>> getClasses()
    {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(JacksonFeature.class);

        return classes;
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers()
    {
        List<User> userList = userDao.getAllUsers();
        Response.Status responseStatus = Response.Status.ACCEPTED;

        return getJSONResponse(responseStatus, userList);
    }

    @POST
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser
    (
            User user
//          @FormParam("id") int id,
//          @FormParam("name") String name,
//          @FormParam("profession") String profession,
//          @Context HttpServletResponse servletResponse
    ) throws IOException
    {
//      User user = new User(id, name, profession);

        boolean userAdded = userDao.addUser(user);

        if(userAdded)
        {
//          return getJSONResponse(Status.CREATED, id);
            return getJSONResponse(Status.CREATED, user.getId());
        }

        //Should be changed to an error response later.
//      return getJSONResponse(Status.CREATED, id);
        return getJSONResponse(Status.CREATED, user.getId());
    }

    public static Response getJSONResponse(Response.Status status, Object entity)
    {
        String json = new Gson().toJson(entity);

        return Response.status(status).entity(json).header("Access-Control-Allow-Origin", "*").build();
    }
}

And got back to Error 415.

Upvotes: 2

Views: 2134

Answers (2)

Maayan Hope
Maayan Hope

Reputation: 1601

Make sure you have this dependency in your project

compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.27'

Upvotes: 3

Ori Marko
Ori Marko

Reputation: 58772

You should declare sending json content type because of the following definition in your code:

 @Consumes(MediaType.APPLICATION_JSON)

So you need to send header with name Content-type and value application/json instead of text/plain

Upvotes: 1

Related Questions