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, 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 );      }};}

Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?