当前位置: 首页 > 面试题库 >

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

堵彬彬
2023-03-14
问题内容

我目前正在将第三方应用程序与我们的本地报告系统集成。我想使用基本身份验证来实现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



 类似资料:
  • 我一直试图用restTemplate传递基本身份验证,但它甚至没有将身份验证头传递给服务器。下面是我使用的bean定义` `

  • 问题内容: 我目前正在将第三方应用程序与我们的本地报告系统集成。我想使用基本身份验证来实现REST调用,但是在Spring 4.0.0中遇到了问题。我有一个简单的解决方案,效果很好: 但想通过以下方式将其重写为使用 ClientHttpRequestFactory : 此代码未编译,因为Spring 4.0.0中不再存在 CommonsClientHttpRequestFactory 类。有人知道

  • 问题内容: 我在RestTemplate中是全新的,基本上在REST API中也是如此。我想通过Jira REST API在我的应用程序中检索一些数据,但返回401未经授权。找到了有关jira rest api文档的 文章,但实际上并不知道如何将其重写为java,因为该示例使用curl的命令行方式。我将不胜感激任何建议或建议如何重写: 使用Spring Rest模板导入Java。其中ZnJlZDp

  • 我知道关于这个主题的讨论已经存在,但我无法找到解决我的情况的答案:我想直接通过URL传递凭据(遵循https://user:pass@URL方案)。我得到一个401错误代码: 有没有比这个答案更简单的线索:使用spring restTemplate对REST API进行基本身份验证? 谢谢

  • 我正在使用Java的spring mvc(基于注释)。我需要在我的应用程序中做rest API。我对API和REST都很陌生。在我的REST应用程序中,所有的基本配置都需要做些什么?我计划使用“RestTemplate”如何用RestTemplate做基本的身份验证(在URL头中传递用户名和密码)?请任何人帮帮我。 提前道谢。

  • 问题内容: 使用基本身份验证进行身份验证时遇到问题。我正在使用符合协议的标准枚举来构造我的请求。问题是,当我在枚举中手动设置授权标头时,如下所示: 我总是收到401未经授权的回复。 但是, 如果我像这样使用回调设置密码: 它正确认证。我希望能够在符合的枚举中手动进行设置,而不是在中传递凭据。 我知道它正在使用身份验证挑战的后台,但我希望能够手动设置它。 这是我的实现: 问题答案: 最终弄清楚了问题