春天4.0.0与RestTemplate基本身份验证 [英] Spring 4.0.0 basic authentication with RestTemplate

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

问题描述

我目前正在与我们的本地报表系统第三方应用程序的集成。我想实现REST与基本身份验证,但在春季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();

但希望改写这个来使用 ClientHtt prequestFactory 以下列方式:

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

这code未编译为 CommonsClientHtt prequestFactory 类不再在Spring 4.0.0存在。难道有人知道任何替代解决方案呢?我很新在这个世界上的REST因此任何帮助将AP preciated。

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.

推荐答案

为什么不检查弹簧4的API,看看哪些类实现所需的接口,即<一个href=\"http://docs.spring.io/spring/docs/4.0.2.RELEASE/javadoc-api/org/springframework/http/client/ClientHtt$p$pquestFactory.html\"相对=nofollow> ClientHtt prequestFactory

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

正如你从Javadoc中看到,最有可能你想要的 HttpComponentsClientHtt prequestFactory ,它使用客户端从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.

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

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