1

I have a little RESTful WebService running on Wildfly 8. Testing @GET works perfectly fine, but @POST won't accept my JSON object. I am having trouble finding out what is wrong in the code and I would appreciate help very much! Where is the error in the code?

The Report Entity:

@Entity
@XmlRootElement
public class Report implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @XmlAttribute
    private Long id;

    @NotNull
    private String reportContent;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getReportContent() {
        return reportContent;
    }

    public void setReportContent(String reportContent) {
        this.reportContent = reportContent;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Report)) {
            return false;
        }
        Report other = (Report) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.myprog.abc.domain.Report[ id=" + id + " ]";
    }
}

The Report Resource:

@Path("report")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReportResource {
    @EJB
    private ReportService rs;

    @GET
    public Response findReports() {
        final List<Report> reports = rs.findAllReports();

        if(reports.size() <= 0)
            throw new NotFoundException("No reports found.");

        return Response.ok(new GenericEntity<List<Report>>(reports) {})
                       .build();
    }

    @GET
    @Path("{id:[1-9][0-9]*}")
    public Response findReport(@PathParam("id") Long id) {
        Report report = rs.findReport(id);

        if(report == null)
            throw new NotFoundException("No report found having the id " + id + ".");

        return Response.ok(report)
                       .build();
    }

    @POST
    public Response createReport(@Valid Report report) {
        rs.saveReport(report);

        return Response.created(URI.create("/" + report.getId()))
                       .build();
    }
}

When testing @GET using http://localhost:8080/abc/rest/report/123 the server returns:

{"reportContent":"This is my Report test content!","id":123}

When testing @POST using http://localhost:8080/abc/rest/report and {"reportContent":"This is my Report test content!"} the server returns:

Status Code: 415 Unsupported Media Type
Connection: keep-alive
Content-Length: 0
Date: Tue, 07 Oct 2014 14:04:55 GMT
Server: WildFly/8
x-powered-by: Undertow/1
Socrates
  • 6,194
  • 14
  • 50
  • 89
  • My question is why do you need post? Is there any specific need for post that you can't do using get? I know with my JSON data, I stay on GET, especially since all I see is you requestinng data, are you actually modifying anything? – DreadHeadedDeveloper Oct 07 '14 at 14:21
  • In fact, here's a link that may help out some http://stackoverflow.com/questions/7160526/jquery-getjson-vs-post-which-one-is-faster – DreadHeadedDeveloper Oct 07 '14 at 14:26
  • 1
    Ok, problem solved setting the header. The code therefore is perfectly fine. Though I don't see any reason why I should put all my data in one GET line instead of cleanly hiding them in POST. I do understand that both works, but where would you see the advanage in GET? – Socrates Oct 07 '14 at 15:34
  • Well for one, POST serves other purposes than that. POST can be used to actually edit data, whereas GET just gets, that's it. In my mind, it's better practice to use the route intended for the action you are doing – DreadHeadedDeveloper Oct 07 '14 at 15:38

2 Answers2

4

I tested your example with jaxrs Client api:

Client client = ClientBuilder.newClient();
    WebTarget myResource = client.target("http://localhost:8080/web/rest/report");
    Report m = new Report();
    m.setId((long) 12);
    m.setReportContent("asdf");
    Entity<Report> report = Entity.json(m);
    Response r = myResource.request(MediaType.APPLICATION_JSON).post(report);
    System.out.println(r.getHeaderString("Location"));

end it gives me propery value in Response location header.

  • 1
    Thanks Peter! My error was not setting `Content-Type` with `application/json` in the header. But still. Thanks a lot for your code sample. That would have been the next think for me to test. :) – Socrates Oct 07 '14 at 15:32
2

Make sure that you have header Content-type in your request. The value must be application/json, since this is the value that you expect.

I'm pretty sure that you are missing it.

Tarlog
  • 9,679
  • 2
  • 41
  • 66
  • 1
    Thanks Tarlog! You were true! My code is perfectly fine. I just missed putting `Content-Type` with `application/json` as header parameter. Thanks a lot! :) – Socrates Oct 07 '14 at 15:30