Httpclient整合Spring教程

2019-03-18|来源:

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);
    }
}


本文参考网络


相关问答

更多

求struts2.0+spring2.0+hibernate3整合视频 带原码+jar包

我又一个s2sh实现的简单小 实例只是实现了登陆,注册的功能 代码,配置,数据库齐全。 后面的东西你自己可以添加

求struts2.0+spring2.0+hibernate3整合视频 带原码+jar包

我又一个s2sh实现的简单小 实例只是实现了登陆,注册的功能 代码,配置,数据库齐全。 后面的东西你自己可以添加

SPRING代替MVC和HIBERNATE整合问题

呵呵,这个是肯定的啊 还有 spring代替MVC这说法你自己想出来的吧? 呵呵,这个spring不是这样用的 如何使用啊?怎么注入。。注入到哪啊? 这个就要你重载下hibernateDaoSupport,这样分页就更方便了,还可以用hibernate的方法 看这个 public class MyHibernateDaoSupport extends HibernateDaoSupport{ @Resource(name="sessionFactory") public void setSuper ...

eclipse下struts+spring+mybatis怎么整合

SSH的整合跟Eclipse并没有什么关系,Eclipse只是IDE工具 整合SSH的话是整合Struts/Hibernate/Spring这三大框架,则需要下载相应的jar包,注意的是三大框架的版本要注意兼容性,尽量下载高版本的jar包,另外也可以通过maven来做jar包管理,防止jar包冲突 最后一般是先整合struts与hibernate,最后与spring整合,整合时需要配置相关的配置文件,这些配置网上一般都有资料

spring3整合hibernate4的问题

你这个问题: 1,spring3整合hibernate4,在dao中都是使用getCurrentSession()来得到session; 2,dao中使用完了session,不要close(); 3,在service中开启事务,随便你使用@Transactional标签还是用XML做AOP都可以;注意必须开启事务,要不getCurrentSession()方法得到的session使用会报错; 4,在web.xml中开启OpenSessionInViewFilter。注意使用org.springfr ...

httpclient 教程

相关文章

更多

最近更新

更多