带有 URL 编码数据的 Spring RestTemplate POST 请求

2023-12-22

我是 Spring 新手,正在尝试使用 RestTemplate 执行休息请求。 Java 代码应执行与以下curl 命令相同的操作:

curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"

但服务器拒绝 RestTemplate400 Bad Request

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);

有人可以告诉我我做错了什么吗?


我认为问题在于,当您尝试将数据发送到服务器时,没有设置内容类型标头,该标头应该是以下两者之一: "application/json" 或 "application/x-www-form-urlencoded" 。在您的情况下是:“application/x-www-form-urlencoded”基于您的示例参数(名称和颜色)。该标头的意思是“我的客户端发送到服务器的数据类型”。

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","feature");
map.add("color","#5843AD");

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

ResponseEntity<LabelCreationResponse> response =
    restTemplate.exchange("https://foo/api/v3/projects/1/labels",
                          HttpMethod.POST,
                          entity,
                          LabelCreationResponse.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 URL 编码数据的 Spring RestTemplate POST 请求 的相关文章

随机推荐