I am using Spring RestTemplate to make HTTP requests
This is my code:
public static ResponseEntity<String> makeRequest() {
ResponseEntity<String> response = null;
try {
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(URI, HttpMethod.GET, null,
String.class);
}catch (HttpStatusCodeException e) {
System.out.println(e.getStatusCode());
}catch (Exception e) {
e.printStackTrace();
}
return response;
}
In the case of a 400 response from the server I am getting an exception and my method returns null value.
Is there any way to make Spring RestTemplate treats 400 HTTP code as 200 ?
For a single place error handling use. Also included import statements
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate() {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(2000);
clientHttpRequestFactory.setReadTimeout(3000);
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override public boolean hasError(ClientHttpResponse response)
throws IOException {
try {
//Do your stuff
return super.hasError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
return true;
}
}
@Override public void handleError(ClientHttpResponse response)
throws IOException {
try {
//Do your stuff
super.handleError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
throw e;
}
}
});
return restTemplate;
}
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