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

2022-09-01 08:02:04

我是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);

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


答案 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);

答案 2

您需要将内容类型设置为 application/json。必须在请求中设置内容类型。下面是用于设置内容类型的修改代码

final String uri = "https://someserver.com/api/v3/projects/1/labels";
String input = "US";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> request = new HttpEntity<String>(input, headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.postForObject(uri, request,  LabelCreationResponse.class);

在这里,HttpEntity是用您的输入(即“US”)和标头构造的。让我知道这是否有效,如果不是,那么请分享例外。干杯!


推荐