I'm making a REST call to an external system from Java. If there are any connection interruptions like if the external system goes offline, I need a listener to detect that and perform corresponding actions. Kindly let me know if I can achieve this in Java. Preferably in Java 8.
Currently i'm not getting any exception if I get into any such situation. I having the below code currently
Client client = ClientBuilder.newClient();
WebTarget target = client.target(HOSTNAME);
Invocation.Builder requestBuilder;
requestBuilder = target.path(URL).request(MediaType.APPLICATION_JSON)
.header(HEADER_AUTHORIZATION, AUTH_TOKEN);
Response response = null;
if (HTTP_POST.equalsIgnoreCase(method)) {
try{
response = requestBuilder.post(Entity.entity(message, MediaType.APPLICATION_JSON_TYPE));
}catch(Exception ex ){
ex.printStackTrace();
}
} else if (HTTP_GET.equalsIgnoreCase(method)) {
response = requestBuilder.get();
}
String executeMessage = null;
if(response != null){
if (response.getStatus() == 200) {
executeMessage = response.readEntity(String.class);
return new JSONObject(executeMessage);
} else {
executeMessage = response.readEntity(String.class);
final JSONObject status = new JSONObject();
status.put(STATUS_CODE, response.getStatus());
status.put(STATUS_INFO, response.getStatusInfo());
status.put("response", executeMessage);
final JSONObject error = new JSONObject();
error.put(ERROR, status);
return error;
}
}
If you use Spring Boot you can try a declarative REST client called Feign:
@FeignClient(url = "example.com", fallback = YourTestFeignClient.YourTestFeignClientFallback.class)
public interface YourTestFeignClient {
@RequestMapping(method = RequestMethod.POST, value = "/example/path/to/resource/{id}")
YourTestResponse requestExternalResource(@RequestParam("id") Long id, SomeRequestDTO requestDTO);
@Component
public static class YourTestFeignClientFallback implements YourTestFeignClient {
@Override
public YourTestResponse requestExternalResource(Long id, SomeRequestDTO requestDTO) {
YourTestResponse testResponse = new YourTestResponse();
testResponse.setMessage("Service unavailable");
return testResponse;
}
}
}
All you need to do here is to inject YourTestFeignClient
in your code and invoke method requestExternalResource
on it. This will call POST example.com/example/path/to/resource/34
with JSON body taken from SomeRequestDTO
. In case a request fails a fallback method inside YourTestFeignClientFallback
will get called, which then returns some default data.
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