Spring RestTemplate POST Request with URL encoded data

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

    You need to set the Content-Type to application/json. Content-Type has to be set in the request. Below is the modified code to set the 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 request = new HttpEntity(input, headers);
    ResponseEntity response = restTemplate.postForObject(uri, request,  LabelCreationResponse.class);
    

    Here, HttpEntity is constructed with your input i.e "US" and with headers. Let me know if this works, if not then please share the exception. Cheers!

提交回复
热议问题