Spring RestTemplate POST Request with URL encoded data

后端 未结 3 834
忘了有多久
忘了有多久 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:40

    It may be a Header issue check if the header is a Valid header, are u referring to "BasicAuth" header?

    HttpHeaders 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 requestBody = new LinkedMultiValueMap();
    requestBody.add("name", "feature");
    requestBody.add("color", "#5843AD");
        
    HttpEntity formEntity = new HttpEntity>(requestBody, headers);
        
    ResponseEntity response = 
       restTemplate.exchange("https://example.com/api/request", HttpMethod.POST, formEntity, LabelCreationResponse.class);
    

提交回复
热议问题