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

问题描述 投票:11回答:3

我是Spring的新手,正在尝试使用RestTemplate发出rest请求。 Java代码应与以下curl命令相同:

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

但是服务器拒绝带有400 Bad Request的RestTemplate

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

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

java spring spring-web
3个回答
19
投票

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

3
投票

您需要将Content-Type设置为application / json。必须在请求中设置Content-Type。下面是修改后的代码,用于设置Content-Type

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”)和标头构造的。让我知道这是否可行,否则请分享例外。干杯!


0
投票

如果标头是有效标头,可能是标头问题,请问您是指“ BasicAuth”标头吗?

HttpHeader headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
    headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //Optional in case server sends back JSON data

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

    HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

    ResponseEntity<LabelCreationResponse> response = 
                    restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, 
                                          formEntity, LabelCreationResponse.class);
© www.soinside.com 2019 - 2024. All rights reserved.