2017-05-28 151 views
1

我檢查了幾種不同的方式,也下載了一個新的項目,看看檢查哪裏是錯誤,但我仍然不知道答案。Spring引導不支持的媒體類型與@RequestBody

這是我RestController

@RestController 
@RequestMapping(value = "/message") 
public class MessageController { 

    @RequestMapping(value = "/", method = RequestMethod.POST) 
    public void createMessage(@RequestBody Message message){ 
     System.out.println(message); 
    } 
} 

這就是我的模型

@Data 
@Entity 
public class Message { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 

    private String sender; 
    private String telephone; 
    private String message; 
} 

搖籃依賴性如果必要

dependencies { 
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.0.pr3' 
    compile('org.springframework.boot:spring-boot-starter-data-jpa') 
    compile('org.springframework.boot:spring-boot-starter-web') 
    runtime('com.h2database:h2') 
    runtime('org.postgresql:postgresql') 
    compileOnly('org.projectlombok:lombok') 
    testCompile('org.springframework.boot:spring-boot-starter-test') 
} 

和郵遞員我收到錯誤

{ 「時間戳」:1495992553884, 「狀態」:415, 「錯誤」: 「不支持的媒體類型」, 「異常」: 「org.springframework.web.HttpMediaTypeNotSupportedException」,
「消息」:「內容鍵入 '應用程序/ x-WWW窗體-urlencoded;字符集= UTF-8' 不支持」,
「路徑」: 「/消息/」}

它是休息但是其中最簡單的方法我犯了一個錯誤?

+1

這可能會幫助你https://stackoverflow.com/questions/33796218/content-type-application-x-www-form-urlencodedcharset-utf-8-not-supported-for – Rohan

+1

'@ RequestBody'用於獲取完整的身體並將其轉化爲該物體。然而,從你的錯誤判斷你只是發佈一個表單,然後你應該使用'@ ModelAttribute'來代替,這是用來將請求參數綁定到對象的。 –

+0

你可以發佈你發佈到web服務的東西嗎? –

回答

2

問題是,當我們使用application/x-www-form-urlencoded時,Spring並不理解它是一個RequestBody。所以,如果我們想要使用它,我們必須刪除@RequestBody註釋。

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 
    public void createMessage(Message message){ 
     //TODO DO your stuff here 
    } 
3

在郵差,身體下,選擇raw並從下拉菜單出現,然後寫JSON作爲請求的身材選擇JSON,您不能使用form-datax-www-form-urlencoded與@RequestBody,他們是當綁定是@ModelAttribute時使用。

相關問題