1

我对 RESTful 很陌生,并试图创建一个示例服务来实现 POST on void 方法。我能够测试 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;
    }       
}
4

1 回答 1

2

您需要像这样注释您的 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;
    }       
}
于 2013-05-18T14:36:12.963 回答