Java Spring RestTemplate URL中的基本身份验证

Java Spring RestTemplate URL中的基本身份验证,java,spring,authentication,resttemplate,Java,Spring,Authentication,Resttemplate,我知道有关于这个主题的现有讨论,但我无法找到我的情况的答案:我想通过URL直接传递凭证(按照方案)。我收到一个401错误,代码如下: final RestTemplate restTemplate = new RestTemplate(); final ResponseEntity<String> wsCalendarResponse = restTemplate.getForEntity("https://user:pass@foobarbaz.com", String.class

我知道有关于这个主题的现有讨论,但我无法找到我的情况的答案:我想通过URL直接传递凭证(按照方案)。我收到一个401错误,代码如下:

final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.getForEntity("https://user:pass@foobarbaz.com", String.class);
final RestTemplate RestTemplate=new RestTemplate();
final ResponseEntity wsCalendarResponse=restTemplate.getForEntity(“https://user:pass@foobarbaz.com”,String.class);
如果我复制。在浏览器中粘贴完全相同的URL(
https://user:pass@foobarbaz.com
),它工作正常

任何比这个答案更简单的线索:


谢谢

嗯,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);
最终字符串urlWs=”https://user:pass@foobarbaz.com”;
最终HttpHeaders=新HttpHeaders();
最终字符串模式=“^(?.+?/)(?.+?):(?.+?)@(?.+)$”;
最终模式regExpPattern=Pattern.compile(模式);
final Matcher Matcher=regExpPattern.Matcher(urlWs);
if(matcher.find()){
最终字符串username=matcher.group(“用户名”);
最终字符串密码=matcher.group(“密码”);
最后一个字符串plainCreds=username+“:”+password;
最终字节[]plainCredBytes=plainCreds.getBytes();
最终字节[]base64CredsBytes=Base64Utils.encode(plainCredsBytes);
最终字符串base64Creds=新字符串(base64CredsBytes);
标题。添加(“授权”、“基本”+base64Creds);
}
最终HttpEntity请求=新HttpEntity(标头);
最终RestTemplate RestTemplate=新RestTemplate();
final ResponseEntity wsCalendarResponse=restTemplate.exchange(urlWs,HttpMethod.GET,request,String.class);

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

答案有用吗?因为RestTemplate和身份验证仍然存在一些问题,Apache客户机无法解决这些问题。