知识点

相关文章

更多

最近更新

更多

Httpclient整合Spring教程

2019-03-18 22:38|来源: 网路

Httpclient和Spring的整合就是把直接new对象的方式改为spring配置即可


1、首先看spring配置文件 spring-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd
       ">
    <!-- <context:property-placeholder location="classpath:config/jdbc.properties"
        ignore-unresolvable="true"/> -->
 
    <context:annotation-config />
    <!-- 配置扫描包 -->
    <context:component-scan base-package="com._656463.httpclient.service" />
 
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 允许JVM参数覆盖 -->
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <!-- 忽略没有找到的资源文件 -->
        <property name="ignoreResourceNotFound" value="true" />
        <!-- 配置资源文件 -->
        <property name="locations">
            <list>
                <value>classpath:httpclient.properties</value>
            </list>
        </property>
    </bean>
 
    <bean id="httpClientConnectionManager"
        class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"
        destroy-method="shutdown">
        <!-- 设置最大连接数 -->
        <property name="maxTotal" value="${http.maxTotal}" />
        <!-- 设置每个主机地址的并发数 -->
        <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
    </bean>
 
    <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
        <property name="connectionManager" ref="httpClientConnectionManager" />
    </bean>
 
    <!-- 通过httpClientBuilder得到httpClient对象,并且要设置httpClient为多例模式 -->
    <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
        factory-bean="httpClientBuilder" factory-method="build" scope="prototype" />
 
    <!-- 构造请求参数 -->
    <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
        <property name="connectTimeout" value="${http.connectTimeout}" />
        <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
        <property name="socketTimeout" value="${http.socketTimeout}" />
        <property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}" />
    </bean>
 
    <bean id="requestConfig" class="org.apache.http.client.config.RequestConfig"
        factory-bean="requestConfigBuilder" factory-method="build" />
 
    <!-- 清理无效连接 -->
    <bean class="com._656463.httpclient.service.IdleConnectionEvictor"
        destroy-method="shutdown">
        <constructor-arg index="0" ref="httpClientConnectionManager" />
    </bean>
</beans>


2、清理无效连接类IdleConnectionEvictor


package com._656463.httpclient.service;
 
import org.apache.http.conn.HttpClientConnectionManager;
 
public class IdleConnectionEvictor extends Thread {
 
    private final HttpClientConnectionManager connMgr;
    private volatile boolean shutdown;
 
    public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
        this.connMgr = connMgr;
        this.start();
    }
 
    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            // 结束
        }
    }
 
    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}



3、httpclient配置文件httpclient.properties

http.maxTotal=200
http.defaultMaxPerRoute=20
 
#创建连接的最长时间
http.connectTimeout=1000
#从连接池中获取连接的最长时间
http.connectionRequestTimeout=500
#数据传输的最长时间
http.socketTimeout=10000
#提交请求前测试连接是否可用
http.staleConnectionCheckEnabled=t


4、把httpclient封装成业务类,并注入CloseableHttpClient和RequestConfig


package com._656463.httpclient.service;
 
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
 
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class HttpClientService {
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig requestConfig;
 
    public String doGet(String url)
            throws URISyntaxException, IOException {
        return doGet(url,null);
    }
 
    public String doGet(String url, Map<String, Object> params)
            throws URISyntaxException, IOException {
        URI uri = null;
        if (params != null) {
            URIBuilder builder = new URIBuilder(url);
 
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                builder.addParameter(entry.getKey(),
                        String.valueOf(entry.getValue()));
            }
            uri = builder.build();
        }
 
        HttpGet httpGet = null;
        if (uri != null) {
            httpGet = new HttpGet(uri);
        } else {
            httpGet = new HttpGet(url);
        }
        httpGet.setConfig(requestConfig);
 
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            System.out.println(httpClient);
            response = httpClient.execute(httpGet);
            // 判断返回状是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
}


5、测试

package com._656463.httpclient;
 
import java.io.IOException;
import java.net.URISyntaxException;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import com._656463.httpclient.service.HttpClientService;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-context.xml")
public class HttpClientTest {
    @Autowired
    private HttpClientService httpClientService;
 
    @Test
    public void test1() throws URISyntaxException, IOException{
        String content = httpClientService.doGet("http://www.baidu.com");
        System.out.println(content);
    }
}


本文参考网络


相关问答

更多
  • 在项目上右键.下面有个myeclipse,移到上面会出现很多选项.先后导入struts,hibernate,spring即可!!!
  • 呵呵,这个是肯定的啊 还有 spring代替MVC这说法你自己想出来的吧? 呵呵,这个spring不是这样用的 如何使用啊?怎么注入。。注入到哪啊? 这个就要你重载下hibernateDaoSupport,这样分页就更方便了,还可以用hibernate的方法 看这个 public class MyHibernateDaoSupport extends HibernateDaoSupport{ @Resource(name="sessionFactory") public void setSuperSessi ...
  • import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MyBatisUtil { private final static SqlSessionFactory sqlSess ...
  • 你这个问题: 1,spring3整合hibernate4,在dao中都是使用getCurrentSession()来得到session; 2,dao中使用完了session,不要close(); 3,在service中开启事务,随便你使用@Transactional标签还是用XML做AOP都可以;注意必须开启事务,要不getCurrentSession()方法得到的session使用会报错; 4,在web.xml中开启OpenSessionInViewFilter。注意使用org.springframewo ...
  • spring
  • 主要是通过Spring管理Hibernate的SessionFactory,Hibernate中的SessionFactory是重量级的线程,而且Spring中提供了对hibernate中dao着了很好的封装,但初学者可以先自己写DAO,但是有了一定的基础的话,用Spring管理DAO或者它自身的DAO,都很好!!Spring对大多ORM框架都有很好的支持,如Ibatis、JPA等等!! Spring用IOC控制DAO,而且可以用AOP一起和hibernate管理事物!!再实际开发中都非常有用的!!