Spring RestTemplate POST Request with URL encoded data

后端 未结 3 848
忘了有多久
忘了有多久 2021-02-18 22:18

I\'m new to Spring and trying to do a rest request with RestTemplate. The Java code should do the same as below curl command:

curl --data \"name=feature&colo         


        
3条回答
  •  渐次进展
    2021-02-18 22:41

    I think the problem is that when you try to send data to server didn't set the content type header which should be one of the two: "application/json" or "application/x-www-form-urlencoded" . In your case is: "application/x-www-form-urlencoded" based on your sample params (name and color). This header means "what type of data my client sends to server".

    RestTemplate restTemplate = new RestTemplate();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("PRIVATE-TOKEN", "xyz");
    
    MultiValueMap map = new LinkedMultiValueMap<>();
    map.add("name","feature");
    map.add("color","#5843AD");
    
    HttpEntity> entity = new HttpEntity<>(map, headers);
    
    ResponseEntity response =
        restTemplate.exchange("https://foo/api/v3/projects/1/labels",
                              HttpMethod.POST,
                              entity,
                              LabelCreationResponse.class);
    

提交回复
热议问题