Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Jersey, how can we 'replace' the status string associated with a known status code?

e.g.

return Response.status(401).build();

generates a HTTP response that contains:

HTTP/1.1 401 Unauthorized

I (not me, but the client application) would like to see the response as:

HTTP/1.1 401 Authorization Required

I tried the following approaches but in vain:

1) This just adds the String in the body of the HTTP response

return Response.status(401).entity("Authorization Required").build();

2) Same result with this too:

ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();

Appreciate your help!

-spd

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

To do this in Jersey you have the concept of WebApplicationException class. One method is to simply extend this class and all one of the methods to set the error text that is returned. In your case this would be:

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;


public class UnauthorizedException extends WebApplicationException {

    /**
      * Create a HTTP 401 (Unauthorized) exception.
     */
     public UnauthorizedException() {
         super(Response.status(Status.UNAUTHORIZED).build());
     }

     /**
      * Create a HTTP 404 (Not Found) exception.
      * @param message the String that is the entity of the 404 response.
      */
     public UnauthorizedException(String message) {
         super(Response.status(Status.UNAUTHORIZED).entity(message).type("text/plain").build());
     }

}

Now in your code that implements the rest service you would simply throw a new exception of this type, passing in the text value in the constructor e.g.

throw new UnauthorizedException("Authorization Required");

That can create a class like this for each of your web exceptions and throw in a similar fashion.

This is also explained in the Jersey user guide - although the code is actually slightly incorrect:

https://jersey.github.io/nonav/documentation/latest/user-guide.html/#d4e435


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...