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

2022-08-31 12:13:57

我实际上是REST WS的新手,但实际上我没有得到这个。415 Unsupported Media Type

我正在Firefox上用Poster测试我的REST,对我来说工作正常,(当它是一个)但是当我尝试它根本没有到达WS时,服务器拒绝它。GETPOSTapplication/xmlapplication/json

这是我的网址:http:// 本地主机:8081/RestDemo/services/customers/add

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

这是我发送的:XML

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

这是我的资源类:

@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;
    }

}

答案 1

添加和在 REST 客户端标头部分Content-Type: application/jsonAccept: application/json


答案 2

问题在于 Bean 客户的反序列化。你的程序知道如何用XML来做,就像Daniel正在写的JAXB一样,但很可能不知道如何用JSON来做。

这里有一个Resteasy/Jackson http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/

泽西岛也是如此:http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/