我开发了一个spring-boot应用程序。当我需要做REST请求(POST,PUT ...)时,我每次都使用基本身份验证
HttpEntity<PostJql> httpEntity = new HttpEntity<PostJql>(post, jiraUtils.getHeader());
ResponseEntity<IssueDataWrapper> response = restTemplate.exchange(urlJiraResponse, HttpMethod.POST, httpEntity, IssueDataWrapper.class);
有没有其他方法可以在应用程序中进行一次基本身份验证,然后在没有基本身份验证的情况下使用RestTemplate或httpPost {Put / Delete ...}?
祝你好运
答案 0 :(得分:2)
是。将RestTemplate
配置为ClientHttpRequestFactory
,以满足您的需求。
您可以在构造函数中设置它:
restTemplate = new RestTemplate(requestFactory);
...或者你可以制作所有这些东西豆子,然后让Spring连接它。
您可以延长SimpleClientHttpRequestFactory
,覆盖createRequest()
:
public class BasicAuthSimpleClientHttpRequestFactory
extends SimpleClientHttpRequestFactory {
@Override
public HttpClientRequest createRequest(URI uri, HttpMethod httpMethod) {
HttpClientRequest request = super.createRequest(uri, httpMethod);
HttpHeaders headers = request.getHeaders();
headers.add(... your auth header ...);
return request;
}
}
...或者您可以将Apache HttpComponents作为依赖项引入并使用HttpComponentsClientHttpRequestFactory
,并配置基础Apache HttpClient
以进行所需的身份验证。 Apache documents this in detail,但是为了帮助您入门:
BasicCredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "password"));
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
RestTemplate restTemplate = new RestTemplate(
new HttpComponentsClientHttpRequestFactory(client));
根据我的经验,如果可以的话,值得引入Apache HttpComponents - 它比HttpUrlConnection
默认使用RestTemplate
的HTTP客户端更可靠和可配置。当您的要求扩展到其他身份验证方法,超时,重试策略等内容时,您会很高兴您有HttpClient
进行配置。