gpt4 book ai didi

java - RestTemplate post值无法传递

转载 作者:行者123 更新时间:2023-12-02 12:02:28 24 4
gpt4 key购买 nike

用restTemplate调用接口(interface),接口(interface)无法接受数据,代码如下`

    Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "xiaohong");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String,Object>> httpEntity = new HttpEntity<Map<String,Object>>(map,headers);

List<HttpMessageConverter<?>> coverterList = new ArrayList<HttpMessageConverter<?>>();
coverterList.add(new MappingJackson2HttpMessageConverter());
coverterList.add(new StringHttpMessageConverter());
coverterList.add(new FormHttpMessageConverter());


String url = "http://127.0.0.1:8099/test/tput/xiaoming";
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(coverterList);
ResponseEntity<Object> result = restTemplate.postForEntity(url, httpEntity, Object.class);








@ResponseBody
@RequestMapping(value="/tput/{age}", method = RequestMethod.POST)
public Object testput(HttpServletRequest request,@PathVariable("age") String age){

// name is null
String name = request.getParameter("name");
System.out.println(name);


Map<String,Object> map = new HashMap<String,Object>();
map.put("name", name);
map.put("age", age);
return map;

`无法获取“名称”的值打印结果:null

最佳答案

restTemplate表单提交需要设置默认的HttpHeaders,`

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("name", "yyyyyyy");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(map,headers);

` 该请求可能会得到

`String name = request.getParameter("name");`

关于java - RestTemplate post值无法传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47149392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com