java - 如何使用@produces 注解?

标签 java rest jakarta-ee annotations jersey

我想在我正在编写的程序中使用 @Produces({Mediatype.Application_XML , Mediatype.Application_JSON}) 。我只想在一种方法上使用它,但我很困惑它什么时候会返回一个 JSON 对象,什么时候会返回一个 XML 页面。这是我正在编写的代码,在这两种情况下,它都会返回一个 XML 提要。如果它不满足 if-else 条件,我希望它返回一个 JSON 对象。

@Path("/{search}")
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) 
public String getCountryData(@PathParam("search") String search,    @QueryParam("ccode") String ccode , @QueryParam("scode") String scode) {

    if(ccode.equals("XML")){
        return "<note> <to>Tove</to> <from>Jani</from><heading>Reminder</heading> <body>Don't forget me this weekend!</body></note>";   
    }   

    return EndecaConn.ConnectDB("Search", search,"mode matchallpartial" );
}

最佳答案

媒体类型将是请求的一部分,您不应将其作为查询参数包含在内。下面是一些示例 Java 代码,它们将数据请求为 application/xml

String uri =
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();

在您的示例中,对于不同的媒体类型,您可以使用对应于相同路径的不同方法。

@Path("/{search}")
@GET
@Produces(MediaType.APPLICATION_JSON) 
public String getCountryDataJSON(@PathParam("search") String search, @QueryParam("scode") String scode) {
    return JSON;
}

@Path("/{search}")
@GET
@Produces(MediaType.APPLICATION_XML) 
public String getCountryDataXML(@PathParam("search") String search, @QueryParam("scode") String scode) {
    return XML;
}

关于java - 如何使用@produces 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17842155/

相关文章:

java - 创建单词对、三元组等以在 Bleu 中进行评估

javascript - NodeJS 创建 REST Post API

c# - http rest api - 如何将响应字符串字段加载到变量

java - Java EE 拦截器是否参与 EJB 的容器管理事务

JavaEE6 : using @Asynchronous to speed up the web application. 什么时候?

java - 无法读取候选组件类: file [%path%/TestEntity.类];嵌套异常是 java.lang.ArrayIndexOutOfBoundsException: 130

java - 在调用方法之前检查非空实际值时出现 NullPointerException

java - JPA:具有复合主键的持久实体

javascript - React js控制componentDidUpdate()方法

java - 为什么这个dataTable sortBy 函数不起作用?