[英]return type xml or json in restful
I have some code below, and when I test it with postman. 我在下面以及与邮递员一起测试时有一些代码。 It occurs an error "500". 发生错误“ 500”。 I don't understand the advantage of "@Produces(MediaType.APPLICATION_XML)". 我不了解“ @Produces(MediaType.APPLICATION_XML)”的优点。 Does it define return type automatically as XML, or not. 是否自动将返回类型定义为XML。
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. 是的,@ @Produce
定义产生的格式。 So your list of users will be format as XML. 因此,您的用户列表将采用XML格式。 Don't forget to parametrize Postman header to accept XML. 不要忘记对Postman标头进行参数设置以接受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 我希望您准备了User类-具有XmlRootElement和XML元素
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 这用来
In your case when an incoming request needs JSON you will get a HTTP 406 as there is nothing that can handle this method. 在您的情况下,当传入请求需要JSON时,您将获得HTTP 406,因为没有什么可以处理此方法。
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. 现在,如果该方法已经用@Produces( {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON} )
进行了注释,那么它将被提供并且将生成JSON。 Now you have single method serving both JSON and XML. 现在,您可以使用提供JSON和XML的单一方法。 What to serve is determined based on the Accept-Header
of the incoming request. 根据传入请求的Accept-Header
确定服务内容。
作为您的方法,结果以xml格式返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.