Follow Step By Step
I added Client Credentials In application.Properties file like below...
http.basicauth.username = yourUserName
http.basicauth.password = yourPassword
And , Then I created one class With two fields Because I'm loading those two fields from the Application.Properties file : username and password . Make sure your class is annotated with @Component..
@Value("${http.basicauth.username}") private String username; @Value("${http.basicauth.password}") private String password;
And Then , You need to autowired above class From Wherever you want..
// I'm getting a username and password from application.properties file String userCredentials = referenceClassName.getUsername()+":"+referenceClassName.getPassword(); // Encoded User Credentials and Convert it into a String String encodedUserCredentials= Base64.getMimeEncoder().encodeToString(userCredentialsBytes.getBytes()); headers.set("Authorization", "Basic " +base64UserCredentials); HttpEntity request = new HttpEntity(headers); String url = "externalUrl"; // Getting a Json String body String body = restTemplate.exchange(url,HttpMethod.GET,request,String.class).getBody(); Note :: For getting an Access Token from String Json body , That's why I converted it into a Json Object JsonObject tokenJsonObject = new JsonParser().parse(body).getAsJsonObject(); // Getting access token as string from tokenJsonObject String accessToken = tokenJsonObject.has("access_token") && !tokenJsonObject.get("access_token").isJsonNull() ? tokenJsonObject.get("access_token").getAsString() : "";
If you have any concerns, please let me know in comments..Hope It will helpful to you..
curl -u fred:fred, no need for clunky manual headers. The same goes for Spring.