Invalid use of BasicClientConnManager: connection still allocated

a 夏天 提交于 2019-11-29 22:51:36

Is there anything wrong I am doing here?

Yes. As stated in the docs:

BasicClientConnectionManager is a simple connection manager that maintains only one connection at a time. Even though this class is thread-safe it ought to be used by one execution thread only. BasicClientConnectionManager will make an effort to reuse the connection for subsequent requests with the same route. It will, however, close the existing connection and re-open it for the given route, if the route of the persistent connection does not match that of the connection request. If the connection has been already been allocated, then java.lang.IllegalStateException is thrown.

BasicClientConnectionManager is used by HttpClient per default.

See "Multithreaded request execution" on how to use a pooling connection manager that can handle requests across multiple threads.

kevinarpe

Assuming you are using the vanilla DefaultHttpClient (which uses BasicClientConnectionManager internally), you first need to consume the outstanding/last response.

EntityUtils.consumeQuietly(httpResponse.getEntity());

Else, you can reallocate DefaultHttpClient each time.

Source: Workaround to not shutdown DefaultHttpClient() each time after usage

This is my configuration for RestTemplate using pool connection manager. It works very well in 5 more concurrent threads.

<!-- RestTemplate -->
<beans:bean id="restTemplateYT" class="org.springframework.web.client.RestTemplate">
    <beans:constructor-arg ref="httpRequestFactoryYT" />
</beans:bean>

<beans:bean id="httpRequestFactoryYT" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"> 
    <beans:constructor-arg>
        <beans:bean class="org.apache.http.impl.client.DefaultHttpClient">
            <beans:constructor-arg>
                <beans:bean class="org.apache.http.impl.conn.PoolingClientConnectionManager"/>
            </beans:constructor-arg>
        </beans:bean>
    </beans:constructor-arg>
    <beans:property name="connectTimeout" value="5000" />
</beans:bean>

Spring version: 3.1.0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!