Tuesday, June 14, 2011

Spring RestTemplate integration with HttpComponents Client

Recently I need to use 'Basic access authentication' with RestTemplate and most of resources pointed to org.springframework.http.client.CommonsClientHttpRequest as base for RestTemplate configuration. But I decided to switch from 'Commons HttpClient' to newer library provided again by Apache community: Apache HttpComponents. So having as example org.springframework.http.client.CommonsClient* classes I started to work and after 1-2 hours it was done. You can find sources here: source and here is small example how to use. First I created class with static factory method:

package info.sargis;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.springframework.http.client.ClientHttpRequestFactory;

import java.net.MalformedURLException;
import java.net.URL;

public class RequestFactoryManager {
    public static ClientHttpRequestFactory createHttpClient(String service, String userName, String password) throws MalformedURLException {
        URL serviceURL = new URL(service);

        DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serviceURL.getHost(), serviceURL.getPort()),
                new UsernamePasswordCredentials(userName, password)
        );

        return new Commons2ClientHttpRequestFactory(httpClient);
    }
}

and here is Spring XML config:

    <bean id="clientHttpRequestFactory" class="info.sargis.RequestFactoryManager" factory-method="createHttpClient">
        <constructor-arg value="${REST_SERVICE_URL}"/>
        <constructor-arg value="${REST_USER_NAME}"/>
        <constructor-arg value="${REST_USER_PASSWORD}"/>
    </bean>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="clientHttpRequestFactory"/>
        <property name="messageConverters">
            <list>
                <bean class="info.sargis.AtomHttpMessageConverter"/>
                <bean class="info.sargis.XMLStringHttpMessageConverter"/>
            </list>
        </property>
    </bean>

And restTemplate bean ready to use :)

No comments:

Post a Comment