API Manager
- API Manager
- All Products
import com.google.gson.Gson; import com.squareup.okhttp."; import java.io.IOException; import java.util.Map; import java.util.concurrent.Timeunit; public class OAuthClientSample ( public static String TEST_API_URL = "https://apigw-pod1.dm-us.informaticacloud.com/t/apim.usw1.com/get_employee_details"; public static String OAUTH_SERVER_URL = "https://dm-us.informaticacloud.com/authz-service/oauth/token"; public static String CLIENT_CREDENTIALS = "YwliT1ZlMWJGRUpsOOhftenFFM8dZdjpRUjQzQXcwbes-"; OkHttpClient client = new OkHttpClient(); public static void main(String [] args) throws Exception { new OAuthClientSample().runApi(); } // // run an OAuth 2.0 in a loop // public void runApi() throws Exception { // // obtain an OAuth 2.0 token for running the API // String token = getNewToken(); while (true) // // run the API using the OAuth 2.0 token // Request request = new Request.Builder() -url(TEST_API_URL) -method("GET", null) -addHeader("Authorization", Bearer + token) -build(); Response response = client.newCall(request).execute(); // // If the token expired, obtain a new token // if (response.code() --401) token = getNewToken (); else System.out.printIn(response.body().string()); Thread.sleep(TimeUnit.SECONDS.toMillis(30)); } } /** * @return a new OAuth 2.0 token from the authentication server * @throws IOException */ String getNewToken() throws IOException { String authHeader = "Basic " + CLIENT_CREDENTIALS; Request request = new request.Builder() -url(AUTH_SERVER_URL + "?grant_type =client_credentials") -method("POST", RequestBody.create(MediaType.parse("text/plain"), "")) -addHeader("Authorization", authHeader) -build(); Response response = client.newCall(request).execute(); if (response.code() != 200) { System.err.printIn(response.code()); System.exit(1); return null; } Map <String, Object> jsonResponse = new Gson().fromJson(response.body().string(), Map.class); return (String)jsonResponse.get("access_token"); } }