是的。用ClientHttpRequestFactory
配置您的RestTemplate
,它可以滿足您的需求。
你可以設置它在構造函數中:
restTemplate = new RestTemplate(requestFactory);
...或者你可以做所有這些事情豆,讓彈簧絲吧。
你可以擴展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
做你需要的認證。阿帕奇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));
在我的經驗是值得引進阿帕奇HttpComponents如果可以的話 - 它更可靠,比HttpUrlConnection
基於HTTP客戶端配置的是RestTemplate
否則默認使用。當您的需求擴展到其他身份驗證方法,超時,重試策略等時,您會很高興您擁有HttpClient
進行配置。