How to do a PUT using RestTemplate - spring

I can do this for POST
ResponseEntity<ResponseMessage> response = restTemplate.postForEntity(URL, animal, ResponseMessage.class);
return response.getBody();
But why there is no putForEntity for PUT? There is just resTemplate.put(...
How do I do it for 'PUT' request.

You can use:
restTemplate.exchange(url, HttpMethod.PUT, requestEntity, ...)
Here is the link to the documentation of this method.

You can use PUT instead, reason why putForEntity is not available because as per standard PUT will not return a response body but 201 or 200 in most of the cases.

Related

How to get pretty formatted output from RestTemplate?

Below is my response from one of the server call from my Spring Boot app,
String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
Then I am returning to client like,
return ResponseEntity.ok().body(result);
In postman I see json is printed with many \" rather pretty formated.
Is there I need to change in response side to see pretty formatted output in Postman?
Sample Postman output:
"{\"records\":[{\"pkg_name\":\"com.company.app\",\"start_time\":1580307656040,\"update_time\":12345,\"min\":0.0,\"create_time\":1580307714254,\"time_offset\":21600000,\"datauuid\":\"xyz\",\"max\":0.0,\"heart_beat_count\":1,\"end_time\":1580307656040,\"heart_rate\":91.0,\"deviceuuid\":\"abc\"}]}" ...
Expected output: Pretty formatted without \"
It seems to me that String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody(); returns double encoded json string. to unescape and get normal json
String unwrappedJSON = objectMapper.readValue(result, String.class);
return ResponseEntity.ok().body(unwrappedJSON);
EDIT
if result is normal json and not double escaped than you can try:
JsonNode result = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class).getBody();
return ResponseEntity.ok().body(result);
The best approach is to create bean and deserializate this String to it.
After it you will have structured object with all benefits. (For example pretty toString method)

What is the replacement of replaceAll(Response) in Response entity?

Response has replaceAll which takes headers(type: MultivaluedMap).
What will be the equivalent code if I want to use ResponseEntity?
Response
.ResponseBuilder
.entity(entityValue)
.replaceAll(headers)
.type(APPLICATION_JSON)
.build();
You can use a constructor with:
new ResponseEntity<>(headers, HttpStatus.OK);
headers is a "MultiValueMap headers".

DELETE in Spring RestTemplate with HttpEntity<List>

I don't know why my code is not working, I've tried with Postman and works fine:
But with RestTemplate I can´t get a response while it´s using the same endpoint... .
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
I've tried with List instead Array[]
When i made a PUT request it´s works fine but with one object:
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);
Any help?? Thanks!!
From the comments it became clear that you're expecting it to return a 400 Bad Request response. RestTemplate will see these as "client errors" and it will throw a HttpClientErrorException.
If you want to handle cases like this, you should catch this exception, for example:
try {
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
} catch (HttpClientErrorException ex) {
String message = ex.getResponseBodyAsString();
}
In this case (since you expect a String), you can use the getResponseBodyAsString() method.
The ResponseEntity will only contain the data in case your request can be executed successfully (2xx status code, like 200, 204, ...). So, if you only expect a message to be returned if the request was not successfully, you can actually do what Mouad mentioned in the comments and you can use the delete() method of the RestTemplate.

HttpHeaders and status value

I have a spring boot application. I use a rest architecture.
I have this method.
#RequestMapping(value = "/members/card/{cardId}", method = RequestMethod.HEAD)
public ResponseEntity hasCardIdValid(#PathVariable(value = "cardId") String cardId) {
return memberService.hasCardIdValid(cardId) ? new ResponseEntity(HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
}
I another application, I would like to call hasCardIdValid method.
I wrote this code
HttpHeaders response = restTemplate.headForHeaders("/rest/members/card/{cardId}", cardId);
I don't find a way to get the 200 or 404 value from response. I don't see any method for that.
Is it possible?
This is because you are getting back HttpHeaders as a result of your restTemplate#headForHeaders() method call.
If you want to get hold of the status you'll have to invoke one of the RestTemplate#exchange() methods instead (there are a few overloaded method signatures) that is giving you back a ResponseEntity on which you can invoke getStatus().

Get request from browser works but using RestTemplate class I got 404 response for the same request

I can easily get the expected JSON response if I send the following get request from my browser:
http://www.bookandwalk.hu/api/AdminTransactionList?password=XXX&begindate=2016-04-30&enddate=2016-10-12&corpusid=HUBW
I tried to use SPRING BOOT 1.4 to create a small demo app to see how rest calls work in Spring.
So I created a POJO representing my domain object and I requested the list of domain objects by the following method invocation:
String startDate=new SimpleDateFormat("yyyy-MM-dd").format(start.getTime());
String endDate=new SimpleDateFormat("yyyy-MM-dd").format(end.getTime());
UriComponents uri=UriComponentsBuilder.newInstance().scheme("http").host("www.bookandwalk.hu").path("/api/AdminTransactionList").queryParam("password","xxx").queryParam("begindate",startDate).queryParam("enddate",endDate).queryParam("corpusid","HUBW").build().encode();
LOG.log(Level.INFO,"{0} were called as a rest call",uri.toString());
ResponseEntity<List<BandWTransaction>> transResponse =
restTemplate.exchange(uri.toString(),
HttpMethod.GET, null, new ParameterizedTypeReference<List<BandWTransaction>>() {
});
List<BandWTransaction> transactions = transResponse.getBody();
I got the following exception:
org.springframework.web.client.HttpClientErrorException: 404 Not Found
As I logged the uri.toString(), I copied it to my browser to double check the is there any typos in my uri but it was working without any failure.
Does Anybody have idea why the same string works from the browser but not from the code?
It seems that you should specify a user agent header in the request for this webapp. Use a HttpEntity object to set this header.
final HttpHeaders headers = new HttpHeaders();
headers.set("User-Agent", "eltabo");
final HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<List<BandWTransaction>> transResponse =
restTemplate.exchange(uri.toString(),
HttpMethod.GET, entity,
new ParameterizedTypeReference<List<BandWTransaction>>() {});
Hope it helps.

Resources