How to configure HttpClient for basic authentication?

I found this sequence to configure basic authentication here :

HttpClient client = new HttpClient();

client.getState().setCredentials(
   new AuthScope("www.domain.com", 443, "realm"),
   new UsernamePasswordCredentials("username", "password") );

How can this be achieved using spring configuration? The reason is because I need to enable authentication for the spring integration of HttpOutboundGateway. The only piece of information I found on this topic is this

  • Question: How to perform spring configuration?
  • And secondly, how can I embed HttpClient in spring integration?
+3
source share
2 answers

Well, it could be something like this: (note, nothing has been verified - it's just a series of random thoughts :))

<bean id="httpOutbound" class="org.springframework.integration.http.HttpOutboundEndpoint" >
    <property name="requestExecutor" ref="executor" />
</bean>

<bean id="executor" class="org.springframework.integration.http.CommonsHttpRequestExecutor">
    <property name="httpClient">
        <bean factory-bean="clientFactory" factory-method="getHttpClient">
    </property>
</bean>

<bean id="clientFactory" class="bla.bla.bla.HttpClientFactoryBean">
    <constructor-arg ref="httpClient" />
    <constructor-arg ref="credentials" />
</bean>

<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
    <constructor-arg ref="httpClientParams" />
</bean>

<bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">
    <property name="authenticationPreemptive" value="true" />
    <property name="connectionManagerClass" value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager" />
</bean>

<bean id="credentials" class="org.apache.commons.httpclient.UsernamePasswordCredentials">
    <constructor-arg value="user" />
    <constructor-arg value="password" />
</bean>


public class HttpClientFactoryBean{
    private HttpClient httpClient;
    public HttpClientFactoryBean(HttpClient httpClient, Credentials credentials){
        this.httpClient = httpClient;
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }

    public HttpClient getHttpClient(){
        return httpClient;
    }
}
+5

FactoryBean, HttpClient .

+1

Source: https://habr.com/ru/post/1775189/


All Articles