我对 RESTful 很陌生,并尝试创建一个示例服务来在 void 方法上实现 POST。我能够测试 String 类的方法,但在使用自定义对象进行测试时出现异常。
服务类别:
@Override
@POST
@Path("/sayHello")
public void sayHello(Person person) {
System.out.println("Hello there, " + person.getName());
}
@Override
@POST
@Path("/sayHi")
public void sayHi(String name) {
System.out.println("Hey there, " + name);
}
测试客户端:
public void testSayHelloRest() throws Exception {
WebClient client = WebClient.create("http://localhost:8080/ServicesTutorial/sampleService/sayHello");
Person p = new Person();
p.setName("My Name");
client.post(p);
}
public void testSayHi() throws Exception {
WebClient client = WebClient.create("http://localhost:8080/ServicesTutorial/sampleService/sayHi");
client.post("My Name");
}
使用简单字符串输入的第二个测试通过,但第一个测试失败并出现以下异常
org.apache.cxf.interceptor.Fault: .No message body writer has been found for class : class com.wk.services.data.Person, ContentType : application/xml.
人员类别
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
最佳答案
您需要像这样注释您的 Person 类:
@XmlRootElement(name="Person")
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class Person {
private String name;
@XmlElement (name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
关于java - CXF-JaxRS WebClient 的自定义对象输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16625174/