[英]POST x-www-form-urlencoded
I've been reading the following and trying to send a POST request with Spring Boot, using RestTemplate.我一直在阅读以下内容并尝试使用 RestTemplate 通过 Spring Boot 发送 POST 请求。
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/x-www-form-urlencoded");
final String body = "clipmessage={ bridgeId: \"" + user.getBridgeId() + "\", clipCommand: { url: \"" + setLightState("3") + "\", method: \"PUT\", body: { \"on\": " + state.isOn() + " } } }";
final String url = API_ADDRESS + user.getAccessToken();
HttpEntity<String> entity = new HttpEntity<>(body, headers);
restTemplate.postForEntity(url, entity, String.class);
If I log the URL and the body and send the exact same in Postman, it succeeds.如果我记录 URL 和正文并在 Postman 中发送完全相同的内容,它会成功。 However, not when I send it from my Spring Boot application.
但是,当我从我的 Spring 引导应用程序发送它时不是这样。
I'm guessing that special body has to be sent in some special way which that I am not aware off?我猜这个特殊的身体必须以某种我不知道的特殊方式发送?
Anyone has any tips on what to try here next?有人对接下来要在这里尝试什么有任何提示吗?
UPDATE 1: I tried the MultiValueMap as suggested, but did not get that to work either.更新 1:我按照建议尝试了 MultiValueMap,但也没有让它工作。
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
final String body = "{ bridgeId: \"" + user.getBridgeId() + "\", clipCommand: { url: \"" + setLightState("3") + "\", method: \"PUT\", body: { \"on\": " + state.isOn() + " } } }";
map.add("clipmessage", body);
HttpEntity<String> entity = new HttpEntity<>(body, headers);
I have the same scenario.我有同样的情况。 solved after using the following code:
使用以下代码后解决:
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
messageConverters.add(formMessageConverter);
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
Parameters and headerpart参数和标题部分
...
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("signature", "signature");
//other parameters
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(parameters, headers);
ResponseEntity<ResponseMessage> responseEntity = restTemplate.postForEntity(url, requestEntity, ResponseMessage.class);
ResponseMessage respMsg =responseEntity.getBody();
logMsg.append(",HTTP STATUS=").append(responseEntity.getStatusCode()).append(", RES:").append(marshal(respMsg));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.