RestTemplate с Basic Auth в Spring 3.1

Мы использовали RestTemplate с конфигурацией xml в Spring 3.0, и он работал отлично.

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

<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory"> 
    <constructor-arg ref="httpClient"/> 
</bean>  

  <bean id="restTemplate" name="restTemplate" class="org.springframework.web.client.RestTemplate" autowire-candidate="true">
        <constructor-arg ref="httpClientFactory" />

    <property name="messageConverters"> 
        <list> 
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            </bean> 
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> 
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
        </list> 
    </property>
  </bean>

Но, когда мы пытаемся перейти на Spring 3.1 релиз, класс CommonsClientHttpRequestFactory устарел, а также commons HttpClient больше не используется.

Я пытался настроить аналогичную конфигурацию, используя класс HttpComponentsClientHttpRequestFactory и Apache HttpClient, но не получая, как я могу установить поставщик учетных данных.

Мы хотим, чтобы httpclient с базовым auth. Кто-нибудь сделал это, или любые указатели были бы большой помощью. Спасибо в Advance.

Ответ 1

Я смог наконец получить эту работу. Не уверен, насколько это оптимально, так как это первое решение, которое сработало для меня.

`             

<!-- Credentials provider needed by apache default http client -->
<bean id="credentialProvider" class="org.apache.http.impl.client.BasicCredentialsProvider" />

<!-- Used to invoke a method in BasicCredentialsProvider.  This has to be done this way as BasicCredentialsProvider does not take 
provider and credentials in constructor or setter method.  It has to set by invoking setCredentials() method and passing two arguments -->  
<bean id="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject"><ref local="credentialProvider" /> </property>
    <property name="targetMethod" value="setCredentials"> </property>
    <property name="arguments"  >
        <list>
            <ref local="authScope" />
            <ref local="credentials" />
        </list>
    </property>
</bean>

<!-- Authorization scope for accessing restful service.  Since we want this template to be used for everything, we are setting up it with defaults -->
<bean id="authScope" class="org.apache.http.auth.AuthScope">
    <constructor-arg name="host"><null /></constructor-arg>
    <constructor-arg><value>-1</value> </constructor-arg>
    <constructor-arg><null /></constructor-arg>
    <constructor-arg><null /></constructor-arg>
</bean>

<!-- Username and Password Credentials to access restful service -->
<bean id="credentials" class="org.apache.http.auth.UsernamePasswordCredentials">
    <constructor-arg name="userName"><value>xxx</value></constructor-arg>
    <constructor-arg name="password"><value>xxx</value></constructor-arg>
</bean>

<!-- Client factory which uses Apache HttpClient implementation.  Note that it DO NOT use apache commons httpclient -->
<bean id="httpClientFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"> 
    <constructor-arg ref="httpClient"/> 
</bean>

<bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient">
    <property name="credentialsProvider" ref="credentialProvider"/>
</bean>

<!-- Rest template for Spring 3.1. Used HttpClientFactory to make request -->
  <bean id="restTemplate" name="restTemplate" class="org.springframework.web.client.RestTemplate" autowire-candidate="true">
        <constructor-arg ref="httpClientFactory" />

    <property name="messageConverters"> 
        <list> 
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            </bean> 
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/> 
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
        </list> 
    </property>
  </bean>`

Ответ 2

Я могу работать с Spring 4 RestTemplate

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="httpClientFactory" />
    </bean>

    <bean id="httpClientFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
         <constructor-arg ref="httpClient" />
    </bean> 

    <bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build" />

    <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
        <property name="defaultRequestConfig" ref="requestConfig" />
        <property name="defaultCredentialsProvider" ref="credentialProvider"/>
    </bean>

    <bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />

    <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig" factory-method="custom">
        <property name="socketTimeout" value="${MILLISEC`enter code here`ONDS}" /> 
        <property name="connectTimeout" value="${MILLISECONDS}" /> 
    </bean> 

<bean id="credentials" class="org.apache.http.auth.NTCredentials">
        <constructor-arg value="${USER}" />
        <constructor-arg value="${PASSWORD}" />
        <constructor-arg value="" />
        <constructor-arg value="${DOMAIN}" />
    </bean>

    <bean id="credentialProvider" class="org.apache.http.impl.client.BasicCredentialsProvider" />

    <!-- This is used to invoke a method in BasicCredentialsProvider.  This has to be done this way as BasicCredentialsProvider does not take 
    provider and credentials in constructor or setter method.  It has to set by invoking setCredentials() method and passing two arguments -->  
    <bean id="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="credentialProvider" /> 
        <property name="targetMethod" value="setCredentials" />
        <property name="arguments"  >
            <list>
                <ref bean="authScope" />
                <ref bean="credentials" />
            </list>
        </property>
    </bean>

    <!-- Authorization scope for accessing restful service. Since we want this template to be used for everything, we are setting up it with defaults -->
    <bean id="authScope" class="org.apache.http.auth.AuthScope">
        <constructor-arg name="host"><null /></constructor-arg>
        <constructor-arg><value>-1</value> </constructor-arg>
        <constructor-arg><null /></constructor-arg>
        <constructor-arg><null /></constructor-arg>
    </bean>