Why is it necessary to return a response object instead of a 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 That's 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 worked fine, but I was told I'd rather return a javax ws. rs.core. Response object, as shown in the following example code It's also good. He said it's the best way to respond to HTTP requests, 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 question is: when you can return a string, is it necessary to return the response object to the HTTP request If necessary, please tell me why, because which is correct for HTTP requests I'm also worried that the response object may give me some problems I may not be able to deal with

Solution

If you return a simple string, you cannot control the error

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 allows you to control other aspects of the HTTP response, such as 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");

In addition, it is much easier to send a file:

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

So there are many reasons. If you don't want to do anything special, if you want to modify the HTTP response properties, just return the object. You must use response

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>