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

新手上路,请多包涵

我是 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 许可协议

阅读 620
1 个回答

我认为问题在于,当您尝试将数据发送到服务器时,没有设置应该是以下两者之一的内容类型标头: “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);

原文由 Nikolay Rusev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题