一尘不染

错误415不支持的媒体类型:如果为JSON,则POST无法到达REST,但如果为XML,则为POST

json

我实际上是REST WS的新手,但实际上我不明白这一点415 Unsupported Media Type

我正在Firefox上用Poster测试我的REST,并且GET对我来说也很好用POST(当它是时application/xml),但是当我尝试application/json它完全无法到达WS时,服务器会拒绝它。

这是我的网址:http:// localhost:8081 / RestDemo / services / customers / add

这是JSON我发送的:{"name": "test1", "address" :"test2"}

这是XML我发送的:

<customer>
    <name>test1</name>
    <address>test2</address>
</customer>

这是我的Resource类:

@Produces("application/xml")
@Path("customers")
@Singleton
@XmlRootElement(name = "customers")
public class CustomerResource {

    private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();

    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<Customer> getCustomers() {
        List<Customer> customers = new ArrayList<Customer>();
        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;
    }

}

阅读 226

收藏
2020-07-27

共1个答案

一尘不染

问题在于bean客户的反序列化。您的程序知道如何使用XML进行编码,就像Daniel所写的那样使用JAXB,但是很可能不知道如何使用JSON进行编码。

在这里,您有Resteasy / Jackson的示例 http://www.mkyong.com/webservices/jax-
rs/integrate-jackson-with-resteasy/

与Jersey相同:http : //www.mkyong.com/webservices/jax-rs/json-example-with-
jersey-jackson/

2020-07-27