简体   繁体   中英

return type xml or json in restful

I have some code below, and when I test it with postman. It occurs an error "500". I don't understand the advantage of "@Produces(MediaType.APPLICATION_XML)". Does it define return type automatically as XML, or not.

import java.sql.SQLException;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/UserService")
public class UserService {
    UserDAO userDAO = new UserDAO();

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_XML)
    public List<User> getUsers() throws ClassNotFoundException, SQLException {
        return userDAO.getAllUsers();
    }

}

Yes, @Produce define the produced format. So your list of users will be format as XML. Don't forget to parametrize Postman header to accept XML.

//To process HTTP GET requests.
 @GET

//@Path Identifies the URI path that a resource class will serve requests for.
 @Path("/abcd")

//@Produces defines the media type(s) that the methods of a resource class can produce.
@Produces(MediaType.APPLICATION_XML

I hope you have prepared the User class - with XmlRootElement and XML elements

for an example -

@XmlRootElement(name="User")
public class User{

    private int id;
    private String name; 

    public User() {

    }


    @XmlElement
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

It specifies the content-types (yes plural!) that this method produces (hence the name). This is used to

  1. select the correct method to execute for an incoming request
  2. determine what to produce as a response.

In your case when an incoming request needs JSON you will get a HTTP 406 as there is nothing that can handle this method.

Now if the method would have been annotated with @Produces( {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON} ) it would be served and JSON would have been produced. Now you have single method serving both JSON and XML. What to serve is determined based on the Accept-Header of the incoming request.

作为您的方法,结果以xml格式返回。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM