我实际上是REST WS的新手,但实际上我没有得到此XML。
我正在Firefox上用Poster测试我的REST,并且XML对我来说也可以正常工作,对{"name": "test1", "address" :"test2"}(对于application/xml)也可以正常工作,但是当我尝试application/json时,它根本无法到达WS,则服务器会拒绝它。
这是我的网址:[http://] localhost:8081 / RestDemo / services / customers / add
这是XML我要发送:{"name": "test1", "address" :"test2"}
我要发送的是XML。
test1
test2这是我的Resource类:
@Produces("application/xml")
@Path("customers")
@Singleton
@XmlRootElement(name = "customers")
public class CustomerResource {
private TreeMap customerMap = new TreeMap();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
@GET
@XmlElement(name = "customer")
public List getCustomers() {
List customers = new ArrayList();
customers.addAll(customerMap.values());
return customers;
}
@GET
@Path("/{id}")
@Produces("application/json")
public String getCustomer(@PathParam("id") int cId) {
Customer customer = customerMap.get(cId);
return "{\"name\": \" " + customer.getName() + " \", \"address\": \"" + customer.getAddress() + "\"}";
}
@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public String addCustomer(Customer customer) {
//insert
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
//get inserted
Customer result = customerMap.get(id);
return "{\"id\": \" " + result.getId() + " \", \"name\": \" " + result.getName() + " \", \"address\": \"" + result.getAddress() + "\"}";
}
}
编辑1:
这是我的客户类:
@XmlRootElement
public class Customer implements Serializable {
private int id;
private String name;
private String address;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}