I am using the spring Framework which has the header below:
import org.springframework.web.client.RestTemplate;
I want to fetch the status code to write my Logger. How do I get the response from restTemplate?
public boolean performTransition(String transitionId,String jiraId){
JiraID id = new JiraID(transitionId);
JiraTransition transition = new JiraTransition();
transition.setTransition(id);
String transitionUrlFormat = String.format(transitionUrl,jiraId);
RestTemplate template = new RestTemplate();
HttpEntity epicEntityRequest = new HttpEntity(transition,createHttpHeaders());
HttpEntity<String> epicEntityResponse= template.exchange(transitionUrlFormat , HttpMethod.POST, epicEntityRequest, String.class);
//TODO: verify code 204
ResponseEntity<String> responseEntity= (ResponseEntity<String>) epicEntityResponse;
epicEntityResponse.getBody();
//System.out.println("LOG" +responseEntity);
//responseEntity.getStatusCode();
HttpStatus statusCode = responseEntity.getStatusCode();
return true;
}
Also, I want to check for the response code above 400 I want write log.warning().
Question needs more elaboration. Are you meaning something like this:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
int statusCode = response.getStatusCode().value();
This gives status code as an int, you can do something like:
if(statusCode > 400){
//Log here
}
The class ResponseEntity
can give you the entire HTTP response status code, body and headers.
Ofcourse, you need to initialize restTemplate
, either using default:
RestTemplate restTemplate = new RestTemplate();
This uses, default: SimpleClientHttpRequestFactory
, or if you want something more configurable you can use: HttpComponentsClientHttpRequestFactory
which has many configs, like connection pooling etc, read timeout, connection timeout etc.