import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Component
public class BasicAuthClient {
private final RestTemplate restTemplate;
public BasicAuthClient(RestTemplateBuilder restTemplateBuilder) {
restTemplate = restTemplateBuilder.build();
}
HttpHeaders createHeaders(String username, String password) {
return new HttpHeaders() {{
final String basicAuth = HttpHeaders.encodeBasicAuth(username, password, StandardCharsets.US_ASCII);
setBasicAuth(basicAuth);
}};
}
private void invokeProtectedResource() {
final ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8080/secured/hello", HttpMethod.GET, new HttpEntity<Void>(createHeaders("admin", "password")), String.class);
System.out.println(responseEntity.getBody());
}
}