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

Young Emil picture Young Emil · Jul 28, 2016 · Viewed 8.9k times · Source

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.

Answer

11thdimension picture 11thdimension · Jul 28, 2016

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.