我是 Spring 的新手,正在尝试使用 RestTemplate 进行休息请求。 Java 代码应执行与以下 curl 命令相同的操作:
curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
但服务器拒绝 RestTemplate 400 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);
有人可以告诉我我做错了什么吗?
原文由 Tobi 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为问题在于,当您尝试将数据发送到服务器时,没有设置应该是以下两者之一的内容类型标头: “application/json” 或 “application/x-www-form-urlencoded” 。在您的情况下是:“application/x-www-form-urlencoded”基于您的示例参数(名称和颜色)。此标头的意思是“我的客户端向服务器发送的数据类型”。