Error 415 when doing json post

Asked

Viewed 597 times

1

I have a CRUD REST application that responded in XML, however, I want to change it and make it respond JSON.

I can do GET in restclient, but POST, PUT and DELETE does not, it gives the Unsupported Media Type error 415. What else should I include in my code for it to work?

Follow the code below:

package pojo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Aluno {
    private int matricula;
    private String nome;
    private Endereco endereco;
    private Curso curso;

    public Aluno() {

    }

    public Aluno(int matricula, String nome, Endereco endereco, Curso curso) {
        super();
        if (!nome.isEmpty())
        {
            this.matricula = matricula;
            this.nome = nome;
            this.endereco = endereco;
            this.curso = curso; 
        }
    }

    public int getMatricula() {
        return matricula;
    }

    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Endereco getEndereco() {
        return endereco;
    }

    public void setEndereco(Endereco endereco) {
        this.endereco = endereco;
    }

    public Curso getCurso() {
        return curso;
    }

    public void setCurso(Curso curso) {
        this.curso = curso;
    }

}

My Cursoresource:

package resources;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import pojo.Curso;
import client.EscolaService;

@Path("curso")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CursoResource {

    private EscolaService escolaService;

    public CursoResource() {
        this.escolaService = new EscolaService();
    }

    @GET
    @Path("{codigo}")
    public Response buscarCurso(@PathParam("codigo") String codigo) {
        Curso curso = escolaService.buscarCurso(new Integer(codigo).intValue());
        if (curso == null) {
            return Response.status(HttpServletResponse.SC_NOT_FOUND).build();
        }

        System.out.println(new Gson().toJson(curso));

        Response resposta = Response.ok(new Gson().toJson(curso)).build();
        return resposta;// coloquei porque estava dando erro
    }

    @POST
    @Consumes("application/json")
    public Response cadastrarCurso(Curso curso) {
        if ((curso.getCodigo() > 0) && (curso.getCodigo() < 100))
        {
            curso = escolaService.cadastrarCurso(curso);
            try {
                return Response.created(new URI("" + curso.getCodigo())).build();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
        }
        Response resposta = Response.ok(new Gson().toJson(curso)).build();
        return resposta.noContent().build();
    }

    @PUT
    public Response alterarCurso(Curso curso) {
        curso = escolaService.alterarCurso(curso);
        try {
            return Response.created(new URI("" + curso.getCodigo())).build();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    @DELETE
    @Path("{codigo}")
    public Response removerCurso(@PathParam("codigo") String codigo) {
        boolean excluir = escolaService.removerCurso(new Integer(codigo)
                .intValue());
        if (excluir == false) {
            return Response.status(HttpServletResponse.SC_NOT_FOUND).build();
        }
        Response resposta = Response.ok().build();
        return resposta;
    }

    @GET
    @Produces("text/plain")
    public String listarCursos() {
        List<Integer> codigos = new ArrayList<Integer>();
        List<String> nomes = new ArrayList<String>();
        for (Iterator<Curso> it = escolaService.listarCursos().iterator(); it
                .hasNext();) {
            Curso curso = (Curso) it.next();
            codigos.add(curso.getCodigo());
            nomes.add(curso.getNome());

        }
        String separador = System.getProperty("line.separator");
        return ("Cursos" +separador+ separador+ "Codigos: " + codigos.toString() +separador+ "Nomes: " + nomes.toString());
    }

}
  • Are you sure the request header is going as application/json? I’ve had problems, for example, when a customer was sending application/json charset=utf-8.

  • Yes, I checked the debug. I think it’s the format I put in the restcliente.. I have tried several ways, such as: {"code":11, "name":"SI" } , and also: {"stroke": {"code":11, "name":"SI" ";}}

  • Another important point is the configuration of the project. When doing the GET you use the library Gson. However, to do the Binding automatic in the parameters, the framework may not be finding the proper library to convert Request to Json. I believe you’re using some implementation of JAX-RS as Jersey right? Jersey uses by default the Jackson library, which must be included in its classpath. The configuration may also be different depending on the version of the framework. For these and others I abandoned JAX-RS and am happy with Spring.

1 answer

-1

Even though doubt is ancient, follow a hint.

Try to use @Produces(MediaType.APPLICATION_JSON) together with the methods of POST, PUT and DELETE.

Example:

@POST
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
public Response cadastrarCurso(Curso curso) {
    if ((curso.getCodigo() > 0) && (curso.getCodigo() < 100))
        {
            curso = escolaService.cadastrarCurso(curso);
            try {
                return Response.created(new URI("" + curso.getCodigo())).build();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
        }
        Response resposta = Response.ok(new Gson().toJson(curso)).build();
        return resposta.noContent().build();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.