java – @Consumes({“application / xml,application / json”})如何编程返回类型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – @Consumes({“application / xml,application / json”})如何编程返回类型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2365字,纯文字阅读大概需要4分钟。
内容图文
![java – @Consumes({“application / xml,application / json”})如何编程返回类型](/upload/InfoBanner/zyjiaocheng/724/808fb65e993a449380f94287c5e3412f.jpg)
我有一个应用程序,我希望它接受XML和JSON,我如何编程返回类型?例如,这是我的POJO
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
// Class to marshall and unmarshall the XML and JSON to POJO
// This is a class for the request JSON and XML
@XmlRootElement
public class KeyProvision {
private String Consumer ;
private String API ;
private String AllowedNames ;
public void setConsumer( String Consumer)
{
this.Consumer= Consumer;
}
public void setAPI( String API){
this.API = API;
}
public void setAllowedNames(String AllowedNames){
this.AllowedNames = AllowedNames;
}
@XmlElement(name="Consumer")
public String getConsumer(){
return Consumer;
}
@XmlElement(name="API")
public String getAPI(){
return API;
}
@XmlElement(name="AllowedNames")
public String getAllowedNames(){
return AllowedNames;
}
}
我的休息界面是
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@POST
@Path("/request")
@Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Response getRequest(KeyProvision keyInfo){
/* StringReader reader = new StringReader(keyInfo); // this code just leads to an execution failure for some reason
try{
JAXBContext jaxbContext = JAXBContext.newInstance(KeyProvision.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
KeyProvision api = (KeyProvision) jaxbUnmarshaller.unmarshal(reader);
System.out.println(api);
} catch(JAXBException e){
e.printStackTrace();
}
*/
String result = "Track saved : " + keyInfo;
return Response.status(201).entity(result).build() ;
// return "success" ;
}
我的XML是
<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>
我的JSON是
{
"KeyProvision": {
"Consumer": "testConsumer",
"API": "posting",
"AllowedNames": "google",
}
}
我的问题是
1)当我使用JSON时,我一直收到415错误,为什么这不能正确解组?
2)JAXB是否确定了重新定型类型?
解决方法:
415 Unsupported Media Type通常是因为,在您的客户端请求中,您没有设置正确的媒体类型标头.在这种情况下,您需要在XML或JSON请求中使用Content-Type:application / xml或Content-Type:application / json.
JAX-RS依赖于Content-Type请求标头来查找正确的JAX-RS Provider以解组传入的请求.
内容总结
以上是互联网集市为您收集整理的java – @Consumes({“application / xml,application / json”})如何编程返回类型全部内容,希望文章能够帮你解决java – @Consumes({“application / xml,application / json”})如何编程返回类型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。