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 ;
94import org .springframework .beans .factory .FactoryBean ;
105import org .springframework .beans .factory .InitializingBean ;
116import org .springframework .http .client .ClientHttpRequestFactory ;
12- import org .springframework .http .client .HttpComponentsClientHttpRequestFactory ;
7+ import org .springframework .http .client .support . BasicAuthorizationInterceptor ;
138import org .springframework .stereotype .Component ;
149import org .springframework .web .client .RestTemplate ;
1510
@@ -40,16 +35,10 @@ public boolean isSingleton() {
4035
4136 @ Override
4237 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 );
38+ HttpHost host = new HttpHost ("localhost" , 8082 , "http" );
39+ final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth (host );
5240 restTemplate = new RestTemplate (requestFactory );
41+ restTemplate .getInterceptors ().add (new BasicAuthorizationInterceptor ("user1" , "user1Pass" ));
5342 }
5443
5544}
0 commit comments