HttpClient

来源:互联网 发布:包贝尔鸡兔同笼算法 编辑:程序博客网 时间:2024/06/05 13:30

1:在common封装一个apiService

package com.mytaotao.common.service;


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


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import com.mytaotao.common.httpclient.HttpResult;


@Service
public class ApiService implements BeanFactoryAware {
    
    @Autowired(required=false)
    private RequestConfig requestConfig;
    
    private BeanFactory beanFactory;
    
    //doget方法
    public String doGet(String url) throws ClientProtocolException, IOException{ // 创建Httpclient对象
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.requestConfig);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = getHttpclient().execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
          
        }
    //带有参数的get请求
    public HttpResult doPost(String url, Map<String, String> params) throws ParseException, IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);


        httpPost.setConfig(this.requestConfig);


        if (!CollectionUtils.isEmpty(params)) {
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = getHttpclient().execute(httpPost);


            HttpEntity entity = response.getEntity();
            if (null == entity) {
                return new HttpResult(response.getStatusLine().getStatusCode(), null);
            }
            return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                    response.getEntity(), "UTF-8"));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        
        
        
    }
    /**
     * 无参的POST请求
     * 
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public HttpResult doPost(String url) throws ParseException, IOException {
        return this.doPost(url, null);
    }
    
    private CloseableHttpClient getHttpclient() {
        return this.beanFactory.getBean(CloseableHttpClient.class);
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
     
        this.beanFactory=beanFactory;
    }
    /**
     * 执行带有参数的POST请求
     * 
     * @param url
     * @param jsonParam
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public HttpResult doPostJson(String url, String jsonParam) throws ParseException, IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);


        httpPost.setConfig(this.requestConfig);


        if (StringUtils.isNotEmpty(jsonParam)) {
            // 构造一个json String 的实体
            StringEntity stringEntity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = getHttpclient().execute(httpPost);


            HttpEntity entity = response.getEntity();
            if (null == entity) {
                return new HttpResult(response.getStatusLine().getStatusCode(), null);
            }
            return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                    response.getEntity(), "UTF-8"));
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
   


}


访问后台系统接口获取

@Service
public class IndexService {
     
    @Autowired
    private ApiService apiService;
    
    @Value("${TAOTAO_MANAGE_URL}")
    private String TAOTAO_MANAGE_URL;
    
    @Value("${INDEX_AD1}")
    private String INDEX_AD1;
    
    @Value("${INDEX_AD2}")
    private String INDEX_AD2;
    
    
    @Value("${INDEX_ITEMAD_LIST}")
    private String INDEX_ITEMAD_LIST;
    
    
    private static final ObjectMapper MAPPER = new ObjectMapper();
     
    @SuppressWarnings("unchecked")
    public String queryIndexAD1() {
        String url=TAOTAO_MANAGE_URL+INDEX_AD1;
        try {
            String jsonData = this.apiService.doGet(url);
            if(StringUtils.isEmpty(jsonData)){
                return null;
            }
          //解析jsonData
            EasyUIResult  easyUIResult= new EasyUIResult().formatToList(jsonData, Content.class);
           List<Object> result = new ArrayList<Object>();
           for (Content content : (List<Content>)easyUIResult.getRows()) {
                    LinkedHashMap<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", content.getPic());
                    map.put("widthB", 550);
                    map.put("href", content.getUrl());
                    map.put("heightB", 240);
                    result.add(map);    
        }
           return MAPPER.writeValueAsString(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String queryIndexAD2() {
        String url=TAOTAO_MANAGE_URL+INDEX_AD2;
        try {
            String jsonData = this.apiService.doGet(url);
            if(StringUtils.isEmpty(jsonData)){
                return null;
            }
          //解析jsonData
            EasyUIResult  easyUIResult= new EasyUIResult().formatToList(jsonData, Content.class);
           List<Object> result = new ArrayList<Object>();
           for (Content content : (List<Content>)easyUIResult.getRows()) {
                    LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("srcB", content.getPic());
                    map.put("height", 70);
                    map.put("alt", content.getTitle());
                    map.put("width", 310);
                    map.put("widthB", 210);
                    map.put("src", content.getPic());
                   
                    map.put("href", content.getUrl());
                    map.put("heightB", 70);
                    result.add(map);    
        }
           return MAPPER.writeValueAsString(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
        
    }
package com.mytaotao.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;
        }
    }


}


package com.mytaotao.manage.pojo;


import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Table(name = "tb_content")
public class Content extends BasePojo {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @Column(name = "category_id")
    private Long categoryId;


    private String title;


    @Column(name = "sub_title")
    private String subTitle;


    @Column(name = "title_desc")
    private String titleDesc;


    private String url;


    private String pic;


    private String pic2;


    private String content;


    public Long getId() {
        return id;
    }


    public void setId(Long id) {
        this.id = id;
    }


    public Long getCategoryId() {
        return categoryId;
    }


    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }


    public String getTitle() {
        return title;
    }


    public void setTitle(String title) {
        this.title = title;
    }


    public String getSubTitle() {
        return subTitle;
    }


    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }


    public String getTitleDesc() {
        return titleDesc;
    }


    public void setTitleDesc(String titleDesc) {
        this.titleDesc = titleDesc;
    }


    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        this.url = url;
    }


    public String getPic() {
        return pic;
    }


    public void setPic(String pic) {
        this.pic = pic;
    }


    public String getPic2() {
        return pic2;
    }


    public void setPic2(String pic2) {
        this.pic2 = pic2;
    }


    public String getContent() {
        return content;
    }


    public void setContent(String content) {
        this.content = content;
    }


}






package com.mytaotao.web.service;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mytaotao.common.httpclient.HttpResult;
import com.mytaotao.common.service.ApiService;
import com.mytaotao.web.bean.Order;
import com.mytaotao.web.bean.User;
import com.mytaotao.web.threadlocal.UserThreadLocal;


@Service
public class OrderService {


    @Autowired
    private ApiService apiService;


    @Value("${TAOTAO_ORDER_URL}")
    private String TAOTAO_ORDER_URL;


    private static final ObjectMapper MAPPER = new ObjectMapper();


    public String submit(Order order) {
        try {
            User user = UserThreadLocal.get();
            order.setUserId(user.getId());
            order.setBuyerNick(user.getUsername());


            String url = TAOTAO_ORDER_URL + "/order/create";
            HttpResult httpResult = this.apiService.doPostJson(url, MAPPER.writeValueAsString(order));
            if (httpResult.getCode().intValue() == 200) {
                JsonNode jsonNode = MAPPER.readTree(httpResult.getBody());
                if (jsonNode.get("status").intValue() == 200) {
                    // 订单提交成功
                    return jsonNode.get("data").asText();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public Order queryOrderById(String orderId) {
        String url = TAOTAO_ORDER_URL + "/order/query/" + orderId;
        try {
            String jsonData = this.apiService.doGet(url);
            if (StringUtils.isNotEmpty(jsonData)) {
                return MAPPER.readValue(jsonData, Order.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

















原创粉丝点击