我有一个Spring MVC应用程序,该应用程序从UI(multiform和json)接收请求,并且必须使用Spring RestTemplate将这些数据发布到另一个微服务中。将请求作为字符串复制到RestTemplate可以在json内容类型的情况下很好地工作,但在多部分情况下似乎不能工作。
这是我的示例代码
Spring MVC控制器:
@Controller
public class MvcController {
@RequestMapping(value = "/api/microservice", method = RequestMethod.POST)
public ResponseEntity<?> callMicroservice(HttpServletRequest request) throws Exception {
RestTemplate rest = new RestTemplate();
String payload = IOUtils.toString(request.getReader());
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", request.getHeader("Content-Type"));
HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
return rest.exchange("https://remote.micrservice.com/api/backendservice", HttpMethod.POST, requestEntity, String.class);
}
}
这里是后端微服务的样子
@Controller
public class RestController {
@RequestMapping(value = "/api/backendservice", method = RequestMethod.POST)
public @ResponseBody Object createService(@RequestParam(value = "jsondata") String jsondata,
@RequestParam(value = "email") String email,@RequestParam(value = "xsltFile", required = false) MultipartFile xsltFile,
HttpServletRequest request) {
// process jsondata
// process xsltFile
// send response
}
}
如果您查看MvcController,我将以字符串形式发送有效负载
String payload = IOUtils.toString(request.getReader());
相反,我如何发送请求数据到RestTemplate请求,以便它同时适用于字符串和多部分。如果您查看MvcController签名,我不知道用户有时会发送什么详细信息,也不知道什么是微服务签名。我只需要在MvcController和RestTemplate请求之间传递数据。
答案 0 :(得分:0)
@RequestMapping(value = "/api/microservice", method = RequestMethod.POST)
public ResponseEntity<?> callMicroservice(HttpServletRequest request) throws Exception {
RestTemplate rest = new RestTemplate();
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("jsondata", yourjsondata);
map.add("email", youremail);
map.add("xsltFile", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
ResponseEntity<String > result = template.get().exchange(
contextPath.get() + path, HttpMethod.POST, requestEntity,
String.class);
}