2013-01-08 39 views
2

我正在做一個Spring MVC控制器,我仍然遇到POST操作的問題。 我已經閱讀了很多解決方案在stackoverflow沒有解決我的問題。Spring MVC 3.1 REST服務post方法返回415

我成就的時刻:

  • 我發送GET請求一個ID,並返回轉化爲成功的JSON對象。
  • 我無法發送POST請求,以此JSON身體,return = 415 UNSUPPORTED_MEDIA_TYPE

1)我加入到我的pom.xml傑克遜API:1.8.5

2)我的Spring配置文件: 我添加了所有必需的部件:

  • 的ViewResolver
  • org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
  • MappingJacksonHttpMessageConverter
  • MVC:註解驅動
  • 掃描我控制器

3)我的模型對象是簡單的:用ID,姓名的帳戶和量

@Document 
public class Account implements Serializable { 

    private static final long serialVersionUID = 9058933587701674803L; 

    @Id 
    private String id; 
    private String name; 
    private Double amount=0.0; 

    // and all get and set methods 

4)最後是我簡化的控制器類:

@Controller 
public class AdminController { 

    @RequestMapping(value="/account", method=RequestMethod.POST, 
      headers = {"content-type=application/json"}) 
    @ResponseStatus(HttpStatus.CREATED) 
    public void addAccount(@RequestBody Account account){ 
     log.debug("account from json request " + account); 
    } 


    @RequestMapping(value="/account/{accountId}", method=RequestMethod.GET) 
    @ResponseBody 
    public Account getAccount(@PathVariable("accountId") long id){ 
     log.debug("account from json request " + id); 
     return new Account(); 
    } 
} 

5)在客戶端,我只是執行命令捲曲: 的成功GET命令:

curl -i -POST -H 'Accept: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account 

任何想法,我要去哪裏錯了:

curl -i -GET -H 'Accept: application/json' http://myhost:8080/compta/account/1 

其失敗的POST命令?

回答

4

試試這個:

curl -i -POST -H "Accept: application/json" -H "Content-type: application/json" -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account 
+0

THX:

Content-Type: application/x-www-form-urlencoded 

只需添加明確Content-Type頭,你是好去。選項-X不會用我的curl命令返回結果。和Contet類型返回另一個錯誤的HTTP狀態:400 – user1842947

6

嗯, 「UNSUPPORTED_MEDIA_TYPE」 應該是一個暗示。你curl命令實際發送:你的回答

curl -v -i -POST -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account 
+0

感謝您的回答,我現在得到另一個錯誤的HTTP狀態400 – user1842947

+1

@ user1842947:這意味着您發送的是不正確的JSON(*錯誤的請求*),Spring MVC無法解析。請提供更多關於您的問題的詳細信息,或者(更好)將此問題標記爲已回答並打開另一個問題。 –

+0

好吧,thx,我嘗試添加我的控制器類在我的問題的更多細節,但我得到有關縮進代碼(4空格)堆棧溢出錯誤消息我嘗試修復它,我會發布它 – user1842947