Consume Rest Api With Basic Authentication 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 , ...