how can i return response status 405 with empty entity?
Asked Answered
S

1

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.

Sought answered 2/7, 2013 at 14:36 Comment(0)
H
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

Hyacinthus answered 2/7, 2013 at 16:18 Comment(5)
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.Sought
@Sought 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();Hyacinthus
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.Sought
@Sought 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.Hyacinthus
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.Sought

© 2022 - 2024 — McMap. All rights reserved.