HttpClient

第一步:导入依赖

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.5</version>
 </dependency>

第二步:httpclient和spring整合applicationContext-httpclient.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 定义连接管理器 -->
	<bean id="httpClientConnectionManager"
		class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"
		destroy-method="close">
		<!-- 设置最大连接数 -->
		<property name="maxTotal" value="${http.maxTotal}" />
		<!-- 设置每个主机地址的并发数 -->
		<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
	</bean>

	<!-- Httpclient构建器 -->
	<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
		<property name="connectionManager" ref="httpClientConnectionManager" />
	</bean>

	<!-- 定义HttpClient对象 -->
	<!-- 该bean一定是多例的 -->
	<bean 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 class="org.apache.http.client.config.RequestConfig"
		factory-bean="requestConfigBuilder" factory-method="build">
	</bean>
	<!-- 定期清理无效连接 -->
	<bean class="com.taotao.web.httpclient.IdleConnectionEvictor" destroy-method="shutdown">
		<constructor-arg index="0" ref="httpClientConnectionManager"/>
		<constructor-arg index="1" value="${http.waitTime}"/>
	</bean>
</beans>
第三步:写httpclient.properties

http.connectionRequestTimeout=500
http.connectTimeout=5000
http.socketTimeout=30000
http.staleConnectionCheckEnabled=true
http.waitTime=300000
http.maxTotal=200
http.defaultMaxPerRoute=100
第四步:spring配置文件了把httpclient.properties添加上

	<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>
				<value>classpath:env.properties</value>
			</list>
		</property>
	</bean>
第五步:写IdleConnectionEvictor类用于定期清理无效的http连接

package com.taotao.web.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;

/**
 * 定期清理无效的http连接
 */
public class IdleConnectionEvictor extends Thread {

    private final HttpClientConnectionManager connMgr;
    
    private Integer waitTime;

    private volatile boolean shutdown;

    public IdleConnectionEvictor(HttpClientConnectionManager connMgr,Integer waitTime) {
        this.connMgr = connMgr;
        this.waitTime = waitTime;
        this.start();
    }

    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(waitTime);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            // 结束
        }
    }

    /**
     * 销毁释放资源
     */
    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}

第六步:写HttpResult

package com.taotao.common.bean;

public class HttpResult {
    private Integer code;

    private String data;

    public HttpResult() {
    }

    public HttpResult(Integer code, String data) {
        this.code = code;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
第七步:封装ApiService

package com.taotao.web.service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.bean.HttpResult;

@Service
public class ApiService {

    @Autowired
    private CloseableHttpClient httpclient;

    @Autowired
    private RequestConfig requestConfig;

    /**
     * 执行GET请求,200返回响应内容,其他状态码返回null
     * 
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String doGet(String url) throws ClientProtocolException, IOException {
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求参数
        httpGet.setConfig(this.requestConfig);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            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;
    }

    /**
     * 指定带有参数的GET请求
     * 
     * @param url
     * @param param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @throws URISyntaxException
     */
    public String doGet(String url, Map<String, String> param) throws ClientProtocolException, IOException,
            URISyntaxException {
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }
        return doGet(builder.build().toString());
    }

    /**
     * 带有参数的post请求
     * 
     * @param url
     * @param param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public HttpResult doPost(String url, Map<String, String> param) throws ClientProtocolException,
            IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        // 设置请求参数
        httpPost.setConfig(this.requestConfig);
        if (null != param) {
            // 设置post参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : param.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                    response.getEntity(), "UTF-8"));
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    /**
     * 执行post请求
     * 
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public HttpResult doPost(String url) throws ClientProtocolException, IOException {
        return doPost(url, null);
    }

}
第八步:EasyUIResult
package com.taotao.common.bean;

import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class EasyUIResult {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private Integer total;

    private List<?> rows;

    public EasyUIResult() {
    }

    public EasyUIResult(Integer total, List<?> rows) {
        this.total = total;
        this.rows = rows;
    }

    public EasyUIResult(Long total, List<?> rows) {
        this.total = total.intValue();
        this.rows = rows;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }

    /**
     * Object是集合转化
     * 
     * @param jsonData json数据
     * @param clazz 集合中的类型
     * @return
     */
    public static EasyUIResult formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("rows");
            List<?> list = null;
            if (data.isArray() && data.size() > 0) {
                list = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return new EasyUIResult(jsonNode.get("total").intValue(), list);
        } catch (Exception e) {
            return null;
        }
    }

}
第九步:IndexService

package com.taotao.web.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.bean.EasyUIResult;
import com.taotao.manage.pojo.Content;

@Service
public class IndexService {
    public static final ObjectMapper MAPPER=new ObjectMapper();
    @Value("${MANAGE_TAOTAO_URL}")
    String MANAGE_TAOTAO_URL;
    @Value("${INDEX_AD1_URL}")
    String INDEX_AD1_URL;
    @Autowired
    private ApiService apiService;
//       //方法一 
//    public String getIndexAd1() {
//        // 通过调用后台系统系统的接口获取数据
//        String url = MANAGE_TAOTAO_URL + INDEX_AD1_URL;
//        try {
//            String jsonData = this.apiService.doGet(url);
//            // 解析json,获取需要的数据
//            // 封装成前端所需的格式
//
//            JsonNode jsonNode = MAPPER.readTree(jsonData);
//            ArrayNode arrayNode = (ArrayNode) jsonNode.get("rows");
//
//            List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
//
//            for (JsonNode node : arrayNode) {
//                Map<String, Object> map = new LinkedHashMap<String, Object>();
//                map.put("srcB", node.get("pic").asText());
//                map.put("height", 240);
//                map.put("alt", node.get("title").asText());
//                map.put("width", 670);
//                map.put("src", map.get("srcB"));
//                map.put("widthB", 550);
//                map.put("href", node.get("url").asText());
//                map.put("heightB", 240);
//
//                result.add(map);
//            }
//            //将java对象序列化成json
//            return MAPPER.writeValueAsString(result);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
        //方法二
        @SuppressWarnings("unchecked")
        public String getIndexAd1() {
          // 通过调用后台系统系统的接口获取数据
          String url = MANAGE_TAOTAO_URL + INDEX_AD1_URL;
          try {
              String jsonData = this.apiService.doGet(url);
              // 解析json,获取需要的数据
              // 封装成前端所需的格式
    
              EasyUIResult easyUIResult=EasyUIResult.formatToList(jsonData, Content.class);
              List<Content> contents=(List<Content>) easyUIResult.getRows();
              List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    
              for (Content content : contents) {
                  Map<String, Object> map = new LinkedHashMap<String, Object>();
                  map.put("srcB", content.getPic());
                  map.put("height", 240);
                  map.put("alt",content.getTitle() );
                  map.put("width", 670);
                  map.put("src", map.get("srcB"));
                  map.put("widthB", 550);
                  map.put("href", content.getUrl());
                  map.put("heightB", 240);
    
                  result.add(map);
              }
              //将java对象序列化成json
              return MAPPER.writeValueAsString(result);
    
          } catch (Exception e) {
              e.printStackTrace();
          }
          return null;
      }
}
第十步:env.properties

MANAGE_TAOTAO_URL=http://manage.taotao.com
INDEX_AD1_URL=/rest/content?categoryId=52&page=1&rows=20
第十一步:IndexController

package com.taotao.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.web.service.IndexService;

@Controller
public class IndexController {
    @Autowired
    private IndexService indexService;
    /**
     * 首页
     */
    @RequestMapping(value="index",method = RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv=new ModelAndView("index");
        //查询大广告数据
        mv.addObject("indexAd1",this.indexService.getIndexAd1());
        return mv;
    }
}
第十二步:页面获取数据

${indexAd1}












  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值