[英]SpringBoot RestController generic POST type
我正在嘗試使用 Spring Boot 構建微服務。
我有一個后端 API,它接收 ResponseEntity POST 請求並對其進行處理(保存到數據庫等)。 其中 Data 是自創建類的對象。
現在我有一個頂級 API(處理身份驗證,..)。 最終用戶將通過這個頂級 API 與后端服務進行通信。 所以這個 API 基本上只需要將所有請求轉發到正確的后端 api。
在這個頂級 API 中,我不想包含我所有的類(例如在這種情況下的 Data 類),我寧願將它作為 String json 數據或其他東西發送。 所以我試過這個:
@RequestMapping(method = RequestMethod.POST, value="/data")
ResponseEntity<String> createUnit(@RequestBody String data) {
URI uri = util.getServiceUrl("dataservice");
String url = uri.toString() + "/data";
ResponseEntity<String> result = restTemplate.postForEntity(url, data, String.class);
return new ResponseEntity<String>(result.getBody(), HttpStatus.OK);
}
但這會導致org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
。
所以我的問題是,有沒有辦法將這些請求轉發到我的后端,而無需在我的 API 中包含所有對象類? 我認為這應該可以,因為這與 Web 瀏覽器以 json 格式發送請求而不知道數據實際上是什么類型的對象時相同。
后端處理如下所示:
@RequestMapping(method = RequestMethod.POST, value="/data")
ResponseEntity<Data> saveData(@RequestBody Data data) {
//Some code that processes the data
return new ResponseEntity<Data>(dataProcessed, HttpStatus.OK);
}
將String
發布到后端服務時,您必須指定Content-Type
標頭,以便 Spring 知道使用哪個HttpMessageConverter
來反序列化Data
對象。
使用RestTemplate
您可以像這樣指定標題:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(data, headers);
restTemplate.postForEntity(url, entity, responseType);
即使問題已經得到解答,我也會展示我設法解決問題的另一種方法。
我使用類型Object
而不是String
:
@RequestMapping(method = RequestMethod.POST, value="/data")
ResponseEntity<Object> createUnit(@RequestBody Object data) {
URI uri = util.getServiceUrl("dataservice");
String url = uri.toString() + "/data";
ResponseEntity<Object> result = restTemplate.postForEntity(url, data, Object.class);
return new ResponseEntity<Object>(result.getBody(), HttpStatus.OK);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.