Spring 4.0.0 使用 RestTemplate 进行基本身份验证 [英] Spring 4.0.0 basic authentication with RestTemplate

查看:56
本文介绍了Spring 4.0.0 使用 RestTemplate 进行基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently working on integration of a third party application with our local reporting system. I would like to implement REST calls with basic authentication but facing issues in Spring 4.0.0. I have a simple solution what works nicely:

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:

but wanted to rewrite this to use ClientHttpRequestFactory in the following way:

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

此代码未编译,因为 CommonsClientHttpRequestFactory 类在 Spring 4.0.0 中不再存在.有人知道任何替代解决方案吗?我在这个 REST 世界中很新,因此任何帮助将不胜感激.

This code is not compiling as the CommonsClientHttpRequestFactory class not exists anymore in Spring 4.0.0. Do somebody know any alternative solution to this? I am quite new in this REST world therefore any help will be appreciated.

推荐答案

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

Why not check the Spring 4 APIs to see which classes implement the required interface, namely ClientHttpRequestFactory?

正如您从 Javadoc 中看到的,您很可能想要 HttpComponentsClientHttpRequestFactory,它使用来自 Apache HttpComponents 的客户端,它是旧公共 HttpClient 的继承者.

As you'll see from the Javadoc, most likely you want HttpComponentsClientHttpRequestFactory, which uses the client from Apache's HttpComponents, the successor to the old commons HttpClient.

这篇关于Spring 4.0.0 使用 RestTemplate 进行基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆