我有一个应用程序,我希望它接受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错误,为什么这不能正确解组?
我的依赖是
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
我将标头设置为Content-Type:application/json
答案 0 :(得分:1)
我猜你没有在你发送给服务的http请求中正确设置内容类型。
我不知道您使用什么工具来创建我建议的请求:
这两种方法都可以让您查看原始的http请求和响应,从而诊断出您的问题。
Generall作为经验法则,在设置请求标头时,冒号和值之间的空格是可取的。即
Content-Type: application/json;
所以样本卷曲请求看起来像这样:
curl -X POST -H "Content-Type: application/json" -d '{"KeyProvision":{"Consumer":"testConsumer","API":"posting","AllowedNames":"google"}}' http://localhost:8080/request
然后Curl将吐出原始请求和响应,以便您可以清楚地看到发生了什么。高级休息客户端也是如此,但也有很多工具可以记住和查看响应/请求。
答案 1 :(得分:0)
尝试将此添加到您的web.xml
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>