我想在我正在编写的程序中使用 @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/