Spring URL 中的 RestTemplate 基本身份验证

Spring RestTemplate Basic authentication in URL

我知道已有关于此主题的讨论,但我找不到适合我的情况的答案:我想通过 URL 直接传递凭据(遵循 https://user:pass@url 方案).我收到此代码的 401 错误:

final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.getForEntity("https://user:pass@foobarbaz.com", String.class);

如果我 copy.paste 在浏览器中 URL 完全相同 (https://user:pass@foobarbaz.com),它工作正常。

任何线索,比这个答案更简单:Basic authentication for REST API using spring restTemplate ?

谢谢

嗯,似乎 Spring RestTemplate 在 URL 中不支持基本身份验证。所以我在 URL 调用之前添加了一些代码,以使其考虑到 URL:

中是否有凭据
final String urlWs = "https://user:pass@foobarbaz.com";
final HttpHeaders headers = new HttpHeaders();
final String pattern = "^(?<protocol>.+?//)(?<username>.+?):(?<password>.+?)@(?<address>.+)$";
final Pattern regExpPattern = Pattern.compile(pattern);
final Matcher matcher = regExpPattern.matcher(urlWs);
if(matcher.find()) {
   final String username = matcher.group("username");
   final String password = matcher.group("password");
   final String plainCreds = username + ":" + password;
   final byte[] plainCredsBytes = plainCreds.getBytes();
   final byte[] base64CredsBytes = Base64Utils.encode(plainCredsBytes);
   final String base64Creds = new String(base64CredsBytes);
   headers.add("Authorization", "Basic " + base64Creds);
}
final HttpEntity<String> request = new HttpEntity<String>(headers);
final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.exchange(urlWs, HttpMethod.GET, request, String.class);

这工作正常,即使没有凭据。