【发布时间】:2019-04-20 03:16:11
【问题描述】:
我有一个 Spring MVC 应用程序,它接受来自 UI(多格式和 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 请求之间传递数据。
【问题讨论】:
标签: spring spring-mvc spring-boot resttemplate