2017-08-10 29 views
0

我在做什麼: 我正在寫一個Java Spring MVC REST API。我試圖發送一個JSON,並根據該數據獲取圖像。Spring MVC Tomcat - 415服務器拒絕請求,因爲請求實體的格式不支持所請求的資源請求的方法

我的問題是什麼
當我發送JSON,下面給出,作爲POST體的application/json的內容類型的一部分,我得到下面

我有什麼所列的415錯誤試圖

  • 切換@RestController@Controller

  • 切換@RequestBody@ModelAttribute

  • 我正在使用PostMan發送數據。我將標題Content-Type包含到application/json,所以它應該將其作爲JSON數據發送。提琴手似乎證實了這一點。

錯誤代碼:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.


控制器代碼:

@RestController 
public class Controller { 

    @RequestMapping(value = "/GrabImage", method = RequestMethod.POST, consumes = "application/json", produces = MediaType.IMAGE_PNG_VALUE) 
    public byte[] GrabImage(@RequestBody Count count){ 
     //code will go here 
    } 
} 

JSON數據:

{ 
    "wordCounts": [ 
    { 
     "word": "Sierra", 
     "count": 50 
    }, 
    { 
     "word": "Love", 
     "count": 25 
    }, 
    { 
     "word": "Dog", 
     "count": 10 
    } 
    ] 
} 

計數類:

public class Count 
{ 
    private WordCounts[] wordCounts; 

    public WordCounts[] getWordCounts() 
    { 
     return wordCounts; 
    } 

    public void setWordCounts (WordCounts[] wordCounts) 
    { 
     this.wordCounts = wordCounts; 
    } 

    @Override 
    public String toString() 
    { 
     return "ClassPojo [wordCounts = "+wordCounts+"]"; 
    } 
} 

字計數類:

public class WordCounts 
{ 
    private int count; 

    private String word; 

    public int getCount() 
    { 
     return count; 
    } 

    public void setCount (int count) 
    { 
     this.count = count; 
    } 

    public String getWord() 
    { 
     return word; 
    } 

    public void setWord (String word) 
    { 
     this.word = word; 
    } 

    @Override 
    public String toString() 
    { 
     return "ClassPojo [count = "+count+", word = "+word+"]"; 
    } 
} 
+0

假設您需要使用'@ ResponseBody'註釋。 –

+0

嘗試使用此公共@ResponseBody字節[] GrabImage(@RequestBody Count count){ code will go here }' –

+0

這產生了相同的錯誤。我沒有想到它會起作用,因爲這涉及RESPONSE機構。發生的事情是RequestBody沒有得到正確的映射,至少從我的看法來看。 –

回答

0

感謝羅西羅賓遜誰幫我弄清楚什麼是錯的。

事實證明,Spring MVC需要Jackson庫來反序列化和序列化對象。只有依賴關係纔會被添加,然後我認爲Spring會提升它們的存在並利用它們。

對於來自未來的人來說,如果你還沒有這樣做,那麼可以嘗試添加Jackson庫。