2014-01-28 63 views
2

我在學習REST風格的Web服務。並且我正在創建一組簡單的Web服務。當我開始開發POST時陷入了困境。如何在REST中創建POST請求以接受JSON輸入?

我想將JSON輸入傳遞給POST方法。這是我在代碼中所做的:

@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded", produces="text/plain") 
@ResponseStatus(HttpStatus.CREATED) 
public @ResponseBody String createChangeRequest(MyCls mycls) { 
    return "YAHOOOO!!"; 
} 

我在我的POM.xml中包含了Jackson。

<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-lgpl</artifactId> 
    <version>1.9.13</version> 
</dependency> 

MyCls是一個簡單的類,有幾個getter和setter。

我從chrome簡單的REST客戶端調用上述POST服務。

URL: http://localhost:8080/MYWS/cls/create 
Data: {<valid-json which corresponds to each variable in the MyCls pojo} 

我看到下面的響應:

415 Unsupported Media Type 
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. 

我嘗試添加標題爲在REST客戶機POST請求「應用/ JSON」 - 但這並沒有幫助。

有人可以讓我知道我在這裏失蹤了嗎?我如何自動將我的輸入JSON映射到MyCls pojo?我在這裏是否缺少任何配置?

編輯: MyCls.java

public class MyCls{ 
    private String name; 
    private String email; 
    private String address; 
     public String getName() { 
    return name; 
    } 
    public void setName(String name) { 
    name= name; 
    } 
     ---similar getter and setter for email, address-- 
} 

從鉻簡單的REST客戶端JSON:

{"name":"abc", "email":"[email protected]","address":"my address"} 

編輯: 改變了我的控制方法以下,但仍出現相同的錯誤:

@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/json", produces="text/plain") 
@ResponseStatus(HttpStatus.CREATED) 
public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) { 
    return "YAHOOOO!!"; 
} 
+0

你能顯示MyCls嗎? – Bart

+0

@Bart - 用MyCls編輯這個問題。java和來自客戶端的JSON – user811433

回答

4

假設您的客戶端正在發送application/json作爲其內容類型,然後處理程序映射到

consumes="application/x-www-form-urlencoded" 

將無法​​處理它。實際的Content-type與預期不符。

如果你期待application/json,則應該有

consumes="application/json" 

此外,聲明

public @ResponseBody String createChangeRequest(MyCls mycls) { 

是(在默認環境),相當於

public @ResponseBody String createChangeRequest(@ModelAttribute MyCls mycls) { 

這意味着MyCls對象是從請求參數創建的,而不是來自JSO N身體。相反,你應該有

public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) { 

讓春天反序列化JSON你對MyCls類型的對象。

+0

對你提出的兩個更改做了修改,但我仍然看到相同的問題。有沒有其他配置,我缺少? – user811433

+0

它看起來像一個傑克遜消息映射器是需要的。這種理解是否正確? – user811433

+0

@user如果Jackson庫位於類路徑上,則默認情況下,您的MVC配置應該註冊它。 –

相關問題