簡體   English   中英

返回415不支持的媒體類型REST客戶端的響應狀態

[英]returned a response status of 415 Unsupported Media Type REST client

我想向REST webservice發出POST請求,我想通過POST請求傳遞客戶java對象 但響應顯示415錯誤代碼不支持的媒體類型。
我的REST客戶端

Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/cthix/rest/v1/m2");

Customer cust = new Customer();
cust.setId(101L);
ObjectMapper mapper = new ObjectMapper();
String jsonCustomer = mapper.writeValueAsString(cust);

ClientResponse restResponse = resource.accept("application/json").
                  post(ClientResponse.class,jsonCustomer);

                    System.out.println(restResponse.getStatus());
                    if(restResponse.getStatus()==200){
                        String output = restResponse.getEntity(String.class);
                        PrintWriter pw = response.getWriter();
                        pw.print(output);

                        pw.flush();
                        pw.close();
                    }

我的REST服務:

@Path(value = "/v1")
public class V1_status {
    @Path("/m2")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Customer returnCustomerDetails(Customer customer){
        Set<Integer> phones = new HashSet<Integer>();
        phones.add(123424541);
        phones.add(123432123);

        List hobbies= new ArrayList();
        hobbies.add("Swimming");
        hobbies.add("coding");;

        customer.setHobbies(hobbies);
        customer.setPhones(phones);
        customer.setCity("Noida");
        customer.setName("abhishek");
        return customer;
    }
}

請指導如何解決它。

我實際上遇到了問題,我錯過的是: resource.type(“application / json”)

ClientResponse restResponse = resource.accept("application/json").type("application/json").post(ClientResponse.class,cust);

需要注意兩點:
1)無需手動將Customer對象轉換為Json。(如果你轉換也沒有問題)

2) 無需使用@Consumes(MediaType.APPLICATION_JSON) 如果你甚至使用它,沒問題。 這只說明,此方法將接受此MediaType。 如果你不使用@Consumes注釋,REST服務方法將嘗試使用它來的任何格式,並將嘗試將來自客戶端的數據解析為其適當的Model對象(在參數中)。 如果成功解析沒問題。 如果數據格式不合適,無法與Model對象同步。 它會拋出異常。 而已。

問題是您告訴服務使用JSON,參數customer是Customer類型,而在REST客戶端中您發送的是字符串。

你需要

  1. 從您的其他服務中刪除“@Consumes(MediaType.APPLICATION_JSON)”
  2. 在客戶端:發送客戶對象(而不是其json表示)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM