使用RestTemplate的Spring 4.0.0基本身份验证


问题内容

我目前正在将第三方应用程序与我们的本地报告系统集成。我想使用基本身份验证来实现REST调用,但是在Spring
4.0.0中遇到了问题。我有一个简单的解决方案,效果很好:

final RestTemplate restTemplate = new RestTemplate();
final String plainCreds = "username:password";
final byte[] plainCredsBytes = plainCreds.getBytes();
final byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
final String base64Creds = new String(base64CredsBytes);

final HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
final HttpEntity<String> request = new HttpEntity<String>(headers);

final ResponseEntity<MyDto> response = restTemplate.exchange("myUrl", HttpMethod.GET, request, MyDto.class);
final MyDto dot = response.getBody();

但想通过以下方式将其重写为使用 ClientHttpRequestFactory

final RestTemplate restTemplate = new RestTemplate(createSecureTransport("username", "password"));

private ClientHttpRequestFactory createSecureTransport(final String username, final String password) {
    final HttpClient client = new HttpClient();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(new AuthScope(null, 9090, AuthScope.ANY_REALM), credentials);
    return new CommonsClientHttpRequestFactory(client);
}

此代码未编译,因为Spring 4.0.0中不再存在 CommonsClientHttpRequestFactory
类。有人知道对此有其他替代解决方案吗?我在这个REST世界中是个新手,因此将不胜感激。


问题答案:

为什么不检查Spring 4
API以查看哪些类实现了所需的接口,即ClientHttpRequestFactory

从Javadoc中可以看到,您很可能想要HttpComponentsClientHttpRequestFactory使用Javadoc
的客户端,该客户端是Apache HttpComponents的客户端,它是旧Commons的继承者HttpClient