发送方代码:
String bizContent = "要发送内容";
String url = appPath + "/receiveData.action";
boolean ecnFlag = true;
Exception ecnException = null;
Map responseMap = null;
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
responseMap = restTemplate.postForObject(url, new HttpEntity<>(bizContent.getBytes("UTF-8"), httpHeaders), Map.class);
}
接收方代码:
@RequestMapping("receiveData.action")
public void receiveData(String jsonStr) {
try {
jsonStr = "接收到内容";
}
}
1、只改发送方:为了确保接收方能够正确接收到 jsonStr 参数,你应该修改发送方的代码以正确地包含该参数在请求中。在你当前的发送方代码中,看起来你正在以 JSON 形式将数据放入请求体中,但参数名未被指定。为了修复这个问题,你应该按照以下方式修改发送方代码:
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
// 修改请求,包含参数名
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("jsonStr", bizContent);
responseMap = restTemplate.postForObject(url, new HttpEntity<>(map, httpHeaders), Map.class);
}
2、只改接收方:如果不改变发送方代码,你可以尝试在接收方代码中修改@RequestMapping注解,以匹配发送方请求的方式。在你提供的接收方代码中,它期望从请求中获取名为 jsonStr 的参数。如果发送方代码没有明确指定参数名,你可以在接收方代码中尝试更改@RequestMapping注解,使用consumes属性来指定请求的Content-Type。
@RequestMapping(value = "receiveData.action", consumes = MediaType.APPLICATION_JSON_VALUE)
public void receiveData(@RequestBody String jsonStr) {
try {
jsonStr = "接收到内容";
}
}