Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is it necessary to return a Response object instead of String object to an http request in java?

I defined my REST method to return a String data type as a response to an http request. This is it:

    @Path("/users/{name}/")
    @GET
    @Produces("application/json")
    public String getAllUserMemberships(@PathParam("name") String name) throws Exception{

        String doc = "{\"name\":\""+name+"\",\"message\":\"Logged in\"}";

        return doc;
    }

It works fine, But I was told by someone to rather return a javax.ws.rs.core.Response object as in the sample code below. This also works fine AND he says it is the best way to respond to an HTTP request But HE DOESN'T KNOW WHY.

    @Path("/users/{name}/")
    @GET
    @Produces("application/json")
    public Response getAllUserMemberships(@PathParam("name") String name) throws Exception{

        String doc = "{\"name\":\""+name+"\",\"message\":\"Logged in\"}";


        return Response.ok(doc, MediaType.APPLICATION_JSON).build();
    }

MY PROBLEM IS: Is it necessary to return a Response object to an HTTP request when you can just return a String. If it is necessary, please tell me why because am in a dilemma as to which one is right for the purpose of HTTP request. I also fear the Response object might give me issues I may not be able to handle.

like image 266
Young Emil Avatar asked Jul 28 '16 15:07

Young Emil


People also ask

What is the use of response object in Java?

The Response object allows you to return http data along with your method's response. For example, a Response object can contain headers, response codes, and other relevant information that a String cannot return on its own. With that said, no, it is not necessary. Your program should function properly with a String.

Is it necessary to return an object in HTTP response?

So there are many reasons, if don't want to do anything special then simply returning object will suffice if you do want to modify the HTTP response properties, then you have to use Response. It is not necessary.

Is it necessary to always return a string in a response?

It is not necessary. But many people prefer to return a Response object always, because you often need to control response headers (beyond those set in the annotations) and other aspects of the response, like the status code. So if you sometimes return a String, and sometimes return a Response, it'll look pretty inconsistent.

What is the use of it in httpresponse?

It is an HTTP status code for the response. The HTTP reason phrase for the response. It is false by default. It is True if the response has been closed. It is used to instantiate an HttpResponse object with the given page content and content type. It is used to set the given header name to the given value. It deletes the header with the given name.


2 Answers

If you return a simple String, you don't have control over what happens in case of error. But if you return Response object you can return a proper 500 error with a fault message:

try {
    return Response.ok(successResult).build();
} catch(Exception ex) {
    return Response.serverError().entity(fault).build();
    //or
    return Response.status(500).entity(fault).build();
}

As others have said, it gives you control over other aspects of a HTTP response like setting some useful headers:

Response response = Response.ok(successResult);

response.getHeaders().put("Access-Control-Allow-Origin", "*");
response.getHeaders().put("Access-Control-Allow-Headers",
        "origin, content-type, accept, authorization");
response.getHeaders().put("Access-Control-Allow-Credentials", "true");
response.getHeaders().put("Access-Control-Allow-Methods",
        "GET, POST, PUT, DELETE, OPTIONS, HEAD");

Also sending a file with this is far easier:

File fileToSend = getFile();
return Response.ok(fileToSend, "application/zip").build();

So there are many reasons, if don't want to do anything special then simply returning object will suffice if you do want to modify the HTTP response properties, then you have to use Response.

like image 174
11thdimension Avatar answered Nov 12 '22 18:11

11thdimension


It is not necessary.

But many people prefer to return a Response object always, because you often need to control response headers (beyond those set in the annotations) and other aspects of the response, like the status code. So if you sometimes return a String, and sometimes return a Response, it'll look pretty inconsistent. Doing it consistently creates a clear and easy-to-follow pattern.

If your app is truly trivial, then it doesn't matter; otherwise, the fact that you are thinking about it suggests that style matters.

like image 40
SusanW Avatar answered Nov 12 '22 18:11

SusanW