I made an HttpClient template that makes using HttpClient a little easier. It converts HttpException to a runtime exception so you don't have to catch errors if you don't want to and the template reduces code a little. It also makes setting up authentication a little easier (beans have no param constructors).
Below are a couple of simple examples and there is more info if you follow the links.
HttpClientTemplate
Code:
<bean id="httpClient" class="org.springbyexample.httpclient.HttpClientTemplate">
<property name="defaultUri">
<value><![CDATA[http://localhost:8093/test]]></value>
</property>
</bean>
The built in callbacks are for String, InputStream, and a byte array (below String callback).
Code:
template.executeGetMethod(new ResponseStringCallback() {
public void doWithResponse(String response) throws IOException {
...
logger.debug("HTTP Get string response. '{}'", response);
}
});
HttpClientOxmTemplate can also marshall and unmarshall responses using Spring Web Service's OXM Framework for marshalling and unmarshalling.
Code:
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="org.springbyexample.schema.beans"/>
</bean>
<bean id="httpClient" class="org.springbyexample.httpclient.HttpClientOxmTemplate">
<property name="defaultUri">
<value><![CDATA[http://localhost:8093/test]]></value>
</property>
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
</bean>
Code:
template.executePostMethod(persons, new ResponseCallback<Persons>() {
public void doWithResponse(Persons persons) throws IOException {
...
Person result = persons.getPerson().get(0);
...
logger.debug("id={} firstName={} lastName={}",
new Object[] { result.getId(),
result.getFirstName(),
result.getLastName()});
}
});