3

How can i return response status 405 with empty entity in java REST?

@POST
@Path("/path")
public Response createNullEntity() {
    return Response.created(null).status(405).entity(null).build();
}

It returns status code 405, but the entity is not null, it is the http page for the error 405.

unor
  • 92,415
  • 26
  • 211
  • 360
junior
  • 33
  • 3

1 Answers1

2

When you return an error status, Jersey delegates the response to your container's error processing via sendError. When sendError is called, the container will serve up an error page. This process is outlined in the Java Servlet Specification §10.9 Error Handling.

I suspect what you are seeing is your container's default error page for a 405 response. You could probably resolve your issue by specifying a custom error page (which could be empty). Alternatively, Jersey won't use sendError if you provide an entity in your response. You could give it an empty string like this:

@POST
@Path("/path")
public Response createNullEntity() {
  return Response.status(405).entity("").build();
}

The above results in Content-Length of 0

Community
  • 1
  • 1
DannyMo
  • 11,344
  • 4
  • 31
  • 37
  • Thank you for your fast answer. I already tried this and i get the same entity (http page for the error 405) and content-lenght 980. – junior Jul 02 '13 at 18:57
  • @junior are you using Jersey? What application server? I tested the above with Tomcat 7.0.39. You might also try a different content-type: `return Response.status(405).entity("").type(MediaType.TEXT_PLAIN).build();` – DannyMo Jul 02 '13 at 19:07
  • i am using jersey 1.17 and tomcat 7.0.12. I tried with different content type and same result. I tried with another status and it is working, i get the result i want. – junior Jul 02 '13 at 20:50
  • @junior When you say you tried with another status, were you calling the same method (the POST at /path `createNullEntity`)? Maybe you're getting an _actual_ 405 error because you're trying to do something other than a POST on that path...have you verified that your method is actually being called? My example works for me, so other than that, I'm out of ideas. – DannyMo Jul 02 '13 at 21:28
  • 2
    i tried on tomcat 7.0.39 and it works, on 6.0.35,7.0.12 and 7.0.22 versions it doesn't work. thank you for your help. – junior Jul 03 '13 at 07:07