2016-12-01 59 views
0

我開發了一個彈簧引導應用程序。當我需要做的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 ...}沒有基本認證?

致以問候

回答

2

是的。用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進行配置。