We have a third part provider that hold our HR data (employee) and I need to retrieve employee data from their RESTful-based API that returns JSON-encoded responses and uses standard HTTP response codes, authentication, and verbs.
This service use OAuth2 protocol.
https://developer.employmenthero.com/api-references/#icon-book-open-introduction
My requirement is to update local database daily basis retrieving data from above service using a java code running in background
Can I consume Json data from a pure java code without a browser?
I'm not much familiar with OAuth2 and having issues with the redirect_url because it's just a java code. Implicit OAuth2 implementation is also an option for me. Is this something achievable?
Can someone provide me some guidelines please.
I have obtained client_id and the secret from this service.
My Sample code is like below..
try {
String clientId = "xxxxxxxxxx";
String clientSecret = "xxxxxxxxxxxxxxxx";
String tokenUrl = "https://oauth.employmenthero.com/oauth2/authorize";
String scope = "read write"; // Optional scope
// Create credentials string (Base64 encoded)
String credentials = clientId + ":" + clientSecret;
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
// Prepare POST data
String postData = "grant_type=client_credentials";
if (scope != null && !scope.isEmpty()) {
postData += "&scope=" + scope;
}
// Create URL object with token endpoint
URL url = new URL(tokenUrl);
// Open connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to POST
connection.setRequestMethod("POST");
// Set the Content-Type header
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
// Enable input/output
connection.setDoOutput(true);
// Write POST data to output stream
connection.getOutputStream().write(postData.getBytes("UTF-8"));
// Get response code
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println("Response: " + response.toString());
// Close connection
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}