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&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
But the server rejects the RestTemplate with a 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);
Can somebody tell me what I'm doing wrong?
String url = "https://app.example.com/hr/email"; Map<String, String> params = new HashMap<String, String>(); params. put("email", "[email protected]"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate. postForEntity( url, params, String. class );
Posting JSON With postForObject. RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.
RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.
Okhttp3 is a quite popular http client implementation for Java and we can easily embed it into Spring RestTemplate abstraction. Following bean declaration will make the default RestTemplete binding instance an Okhttp3 client. You can just autowire the Resttemplate to use this customized Okhttp3 based resttemplate.
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<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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With