Skip to content

Instantly share code, notes, and snippets.

@ldclakmal
Last active April 22, 2018 18:58
Show Gist options
  • Save ldclakmal/f1a1d1c57903dd61e7ff11b0fe9863b7 to your computer and use it in GitHub Desktop.
Save ldclakmal/f1a1d1c57903dd61e7ff11b0fe9863b7 to your computer and use it in GitHub Desktop.
Call REST API
private Optional<JsonObject> callRestApi(String url) {
try {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(System.getenv(Constant.EnvironmentVariable.USERNAME),
System.getenv(Constant.EnvironmentVariable.PASSWORD));
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpResponse response = client.execute(new HttpGet(url));
String json = EntityUtils.toString(response.getEntity(), "UTF-8");
JsonElement jsonElement = new JsonParser().parse(json);
return Optional.of(jsonElement.getAsJsonObject());
} catch (IOException e) {
logger.error("Failed to call api {}", url, e);
return Optional.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment