11package org .baeldung .client ;
22
3- import org .apache .http .auth .AuthScope ;
4- import org .apache .http .auth .UsernamePasswordCredentials ;
5- import org .apache .http .client .config .RequestConfig ;
6- import org .apache .http .impl .client .BasicCredentialsProvider ;
7- import org .apache .http .impl .client .CloseableHttpClient ;
8- import org .apache .http .impl .client .HttpClientBuilder ;
3+ import org .apache .http .HttpHost ;
4+ import org .baeldung .http .client .HttpComponentsClientHttpRequestFactoryBasicAuth ;
95import org .springframework .beans .factory .FactoryBean ;
106import org .springframework .beans .factory .InitializingBean ;
117import org .springframework .http .client .ClientHttpRequestFactory ;
12- import org .springframework .http .client .HttpComponentsClientHttpRequestFactory ;
8+ import org .springframework .http .client .support . BasicAuthorizationInterceptor ;
139import org .springframework .stereotype .Component ;
1410import org .springframework .web .client .RestTemplate ;
1511
@@ -40,16 +36,10 @@ public boolean isSingleton() {
4036
4137 @ Override
4238 public void afterPropertiesSet () {
43- final int timeout = 5 ;
44-
45- final RequestConfig config = RequestConfig .custom ().setConnectTimeout (timeout * 1000 ).setConnectionRequestTimeout (timeout * 1000 ).setSocketTimeout (timeout * 1000 ).build ();
46-
47- final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider ();
48- credentialsProvider .setCredentials (new AuthScope ("localhost" , 8082 , AuthScope .ANY_REALM ), new UsernamePasswordCredentials ("user1" , "user1Pass" ));
49- final CloseableHttpClient client = HttpClientBuilder .create ().setDefaultRequestConfig (config ).setDefaultCredentialsProvider (credentialsProvider ).build ();
50-
51- final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory (client );
39+ HttpHost host = new HttpHost ("localhost" , 8082 , "http" );
40+ final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth (host );
5241 restTemplate = new RestTemplate (requestFactory );
42+ restTemplate .getInterceptors ().add (new BasicAuthorizationInterceptor ("user1" , "user1Pass" ));
5343 }
5444
5545}
0 commit comments