今天在用RestTemplatet
发送post请求传参的时候发现参数怎么也收不到,尝试了好多办法,网上也搜了好多都没解决问题
下面贴一下最后解决的代码
发送端:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON_UTF8);
//我这里request.getHeaderNames()是从别的请求获取的参数,不用关注这里
Enumeration<String> headers = request.getHeaderNames();
while (headers.hasMoreElements()){
String key = headers.nextElement();
header.add(key,request.getHeader(key));
}
//一定要用MultiValueMap别的不起作用
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
Enumeration<String> parameters = request.getParameterNames();
while (parameters.hasMoreElements()){
String key = parameters.nextElement();
if(!targetUrl.equals(key)){
LinkedList<Object> param = new LinkedList<>();
param.add(request.getParameter(key));
body.put(key,param);
}
}
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body,header);
ResponseEntity<String> response = restTemplate.postForEntity(url,entity,String.class);
return response.getBody();
接收端:
有说用@RequestBody
也有说用@RequestParam
的,我试了我这必须是@RequestBody
才能收到值ParamMap
是我封装的一个map,方便取值,下面也贴源码了
@PostMapping(value = "/adddjrjh",produces = { "application/json;charset=UTF-8" })
private R adddjrjh(@RequestBody ParamMap<String,Object> params) throws Exception {
System.out.println(params.getParamter("djrjh"));
return R.setResult(BAD_SQL_GRAMMAR);
}
ParamMap:
public class ParamMap<K,V> extends LinkedHashMap {
public String getParamter(String param){
if(null!=this.get(param)){
return String.valueOf(((ArrayList)this.get(param)).get(0));
}else{
return null;
}
}
}
如果你的问题已经解决,很开心能够帮助到你~