I'm experimenting with building microservices using Spring Boot.
I have a back-end API that receives ResponseEntity POST requests and processes it (saving to database etc). Where Data is an Object of a self-created class.
Now I have a top-level API (that handles authentication,..). The end-users will communicate with the back-end services through this top-level API. So this API basically just has to forward all the requests to the right back-end api's.
In this top API I don't want to need to include all my classes (eg the Data class in this case) and I would rather just send it as String json data or something. So I tried this:
@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);
}
But this results in an org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
.
So my question is, is there a way to forward these requests to my back-end without the need to include all my Object classes in my API? I figured this should be able since this is the same as when a web-browser sends requests in json format without knowing what kind of Object the data actually is.
The back-end handling looks like this:
@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);
}
When posting the String
to the backend service you have to specify the Content-Type
header so Spring knows which HttpMessageConverter
to use to deserialize the Data
object.
With RestTemplate
you can specify the header like this:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(data, headers);
restTemplate.postForEntity(url, entity, responseType);
Even though the question was already answered, I'll show another way I managed to solve the problem.
I used type Object
instead of 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.