consuming rest api with basic authentication by resttemplate in spring boot code example

Example 1: set autorization basic with username and password + resttemplate

try {
    // request url
    String url = "https://jsonplaceholder.typicode.com/posts";

    // create auth credentials
    String authStr = "username:password";
    String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    // create request
    HttpEntity request = new HttpEntity(headers);

    // make a request
    ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);

    // get JSON response
    String json = response.getBody();

} catch (Exception ex) {
    ex.printStackTrace();
}

Example 2: resttemplate authorization basic

HttpHeaders createHeaders(String username, String password){   return new HttpHeaders() {{         String auth = username + ":" + password;         byte[] encodedAuth = Base64.encodeBase64(             auth.getBytes(Charset.forName("US-ASCII")) );         String authHeader = "Basic " + new String( encodedAuth );         set( "Authorization", authHeader );      }};}