如何 - Spring IoC和HttpClient 4.3.1 CloseableHttpClient?

时间:2013-12-03 00:16:52

标签: java spring apache-httpclient-4.x

我想让Spring IoC配置一个CloseableHttpClient对象并将其注入我的类中,以便可以通过XML完成其配置的自定义。

从我所看到的情况来看,HttpClient似乎非常强烈地抵制这种模式。他们希望你做像

这样的事情
CloseableHttpClient chc =
    HttpClients.custom().set<thing that should be a property>().build();

伊克。

是否有一些制作单例CloseableHttpClient bean的机制,我可以使用它?

2 个答案:

答案 0 :(得分:40)

这似乎对我有用:

<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig"
    factory-method="custom">
    <property name="socketTimeout" value="${socketTimeoutInMillis}" /> 
    <property name="connectTimeout" value="${connectionTimeoutInMillis}" /> 
</bean>

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

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

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

这给了我一个“httpClient”bean中的CloseableHttpClient,配置了套接字和连接超时。您应该能够向requestConfigBuilder或httpClientBuilder添加更多属性。

答案 1 :(得分:8)

使用Java配置,这就像

一样简单
@Bean
public CloseableHttpClient httpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setEverything(everything); // configure it
    CloseableHttpClient httpClient = builder.build();
}

使用XML配置,它有点复杂。您可以创建自己的FactoryBean实施,例如CloseableHttpClientFactoryBean,将所有来电委托给HttpClientBuilder并在build()内调用getObject()

public class CloseableHttpClientFactoryBean implements FactoryBean<CloseableHttpClient> {
    private HttpClientBuilder builder;
    public CloseableHttpClientFactoryBean() {
        builder = HttpClientBuilder.create();
    }

    ... // all the setters
    // for example
    public void setEverything(Everything everything) {
        // delegate
        builder.setEverything(everything);
    }

    public CloseableHttpClient getObject() {
        return builder.build();
    }
}

和配置

<bean name="httpClient" class="com.spring.http.clients.CloseableHttpClientFactoryBean">
    <property name="everything" ref="everything"/>
</bean>

每个HttpClientBuilder方法都需要一个setter方法。

请注意,如果您不需要任何自定义配置,则可以使用factory-method获取默认CloseableHttpClient

<bean name="httpClient" class="org.apache.http.impl.client.HttpClients" factory-method="createDefault" >
</bean>