JavaSpringBootRestTemplate。postForObject参数为空
我有两个spring boot应用程序,一个作为前端运行,另一个作为后端服务运行。从前端我对后端服务进行api调用,我发送的两个参数都显示为null。我认为问题在于rest模板
更新
所以我注意到,如果我省略了内容值,那么它就会起作用。由于内容是大于1mb的文件的内容,我在应用程序中添加了以下内容。yml:
spring.servlet.multipart.max-file-size: 10MB
spring.servlet.multipart.max-request-size: 10MB
以下是我的代码,我在本期中发布的代码基础上进行了更新: How to POST form data with Spring RestTemplate?
但是我仍然没有在后端控制器中获取值,而是两个值都为null
public void upload(byte[] content, String name) {
String encodedString = Base64.getEncoder().encodeToString(content);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("fileName", name);
map.add("content", encodedString);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(backendUrl + "/upload", request, String.class);
log.debug("Response from upload: " + response);
}
这是后端的控制器。文件名和内容均为空:
@CrossOrigin
@SneakyThrows
@ResponseBody
@PostMapping(value = "/upload")
public ResponseEntity<String> upload(@ModelAttribute FormModel form) {
byte[] decodedBytes = Base64.getDecoder().decode(form.getContent());
uploadService.upload(decodedBytes, form.getFileName());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Content-Type", "application/json");
return ResponseEntity.ok().headers(responseHeaders).body("Uploaded");
}
谁能看看这个代码有什么问题吗
提前谢谢
# 1 楼答案
我想问题是您试图使用
restTemplate.postForObject
,但是使用@RequestParam
而不是@RequestBody
在
@RequestParam
中,您希望在查询参数/upload?fileName=&content=
中接收数据。但是你实际上是用restTemplate.postForObject(backendService+ "/upload", map, String.class);
在身体里发送它所以我的建议是改变
public ResponseEntity<String> upload(@RequestParam(value = "fileName") String fileName, @RequestParam(value = "content") String content)
到
public ResponseEntity<String> upload(@RequestBody Map<String, String> body)
然后从正文中获取文件名和文件内容
# 2 楼答案
好的,我可以通过发送和接收字节而不是编码为字符串的字节来修复它。 因此,在resttemplate中:
在控制器中:
不过,如果能知道为什么以前的版本不起作用,那就太好了