RestTemplate Equivalent of cURL PUT

958 Views Asked by At

I can access an API with that cURL command:

curl -X PUT -H 'Content-type:application/json' --data-binary '["remaro"]' "http://localhost:4352/mypath"

I want to make it over Spring RestTemplate. My data is stored as String. I tried that but my server returns 400 bad request:

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<>("\"" + dataVariable + "\"", headers);
restTemplate.put(http://localhost:4352/mypath, entity);

I've also send my variable as:

String dataVariable = "\"remaro\"";

but didn't work. I still get 400 error.

2

There are 2 best solutions below

0
On

Use RestTemplate.exchange

Look at my example and change accordingly

String url = BASE_URI + "/update/{clusterId}";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);


ClusterDTO cluster = new ClusterDTO();
cluster.setClusterId(1L);
cluster.setClusterName("ClusterAV");
..........

HttpEntity<ClusterDTO> entity = new HttpEntity<ClusterDTO>(cluster,headers);
ResponseEntity<ClusterDTO> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ClusterDTO.class,1L);
0
On

I've just send it as:

"[\"" + dataVariable + "\"]"

and worked.