美文网首页
java 对http网络请求的基础封装

java 对http网络请求的基础封装

作者: huangxiongbiao | 来源:发表于2017-05-11 08:34 被阅读59次

    1、对外接口

    package com.hm.service;
    import java.util.Map;
    import com.hm.web.model.SerializeObject;
    
    /**
     * 数据操作基类实现类
     */
    public interface BaseService {
        
        /**
         * 根据ID获取资料
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @return          操作结果
         */
        public SerializeObject find(String sessionID, Map<String, String[]> params);
        
        /**
         * 新增或修改
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @return          操作结果
         */
        public SerializeObject update(String sessionID, Map<String, String[]> params);
    
        /**
         * 删除
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @return          操作结果
         */
        public SerializeObject delete(String sessionID, Map<String, String[]> params);
    
        /**
         * 验证法庭是否存在
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @return          是否验证通过
         */
        public SerializeObject verify(String sessionID, Map<String, String[]> params);
        
        /**
         * 查询
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @return          分页数据
         */
        public SerializeObject query(String sessionID, Map<String, String[]> params);
        
        /**
         * 查询返回DataTable
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @param key       根据key获取接口URL地址
         * @return          分页数据
         */
        public SerializeObject queryToDataTable(String sessionID, Map<String, String[]> params, String key);
    
        /**
         * 查询返回List
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @param key       根据key获取接口URL地址
         * @return          数据
         */
        public SerializeObject queryToList(String sessionID, Map<String, String[]> params, String key);
        
        /**
         * 查询返回String
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @param key       根据key获取接口URL地址
         * @return          分页数据
         */
        public SerializeObject queryToString(String sessionID, Map<String, String[]> params, String key);
        
        /**
         * 查询返回Object
         * @param sessionID 登录成功后分配的Key
         * @param params    参数集合
         * @param key       根据key获取接口URL地址
         * @return          分页数据
         */
        public SerializeObject queryToObject(String sessionID, Map<String, String[]> params, String key);
        
        /**
         * 查询放回Object
         * @param sessionID
         * @param params
         * @param beanClass 定义类型
         * @return
         */
        public SerializeObject queryObject(String sessionID, Map<String, String[]> params, String key,Class<?> beanClass);
        
        /**
         * 查询放回Object
         * @param sessionID
         * @param params
         * @param beanClass 定义类型
         * @return
         */
        public SerializeObject queryToDataTableObject(String sessionID, Map<String, String[]> params, String key, Class<?> beanClass);
    }
    
    

    2、基础实现

    package com.hm.service.impl;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import net.sf.json.JsonConfig;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    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 com.hm.common.util.UF;
    import com.hm.data.ResultType;
    import com.hm.service.BaseService;
    import com.hm.service.bean.DataTable;
    import com.hm.service.bean.HousesBean;
    import com.hm.service.bean.Page;
    import com.hm.web.cache.ServiceUriCache;
    import com.hm.web.config.WebConfig;
    import com.hm.web.model.SerializeObject;
    
    /**
     * 数据操作基类实现类
     */
    public class BaseServiceImpl implements BaseService{
    
        private static Log log;
        private String entityName = "";
        private Class<?> entityClass;
        
        ServiceUriCache serviceUriCache = ServiceUriCache.getInstance();
        
        /**
         * 返回格式:{"status":500,"data":"message"}
         * @param jsonText  JSON字符串
         * @return          操作结果
         */
        public SerializeObject parseSerializeObject(String jsonText) {
            if(StringUtils.isBlank(jsonText)) {
                return null;
            }
            
            int status = ResultType.ERROR;
            String data = "";
            try{
                JSONObject obj = JSONObject.fromObject(jsonText);
                if(null != obj) {
                    status = UF.toInt(obj.get("status").toString());
                    data = UF.toString(obj.get("data").toString());
                }
            } catch (Exception e) {
                getLog().error(e.getMessage());
                return null;
            }
            return new SerializeObject(status, data);
        }
        
        /**
         * 根据Class<?> beanClass,返回执行结果。<br/>
         * 返回格式:{"status":500,"data":Class}
         * @param jsonText  JSON字符串
         * @param beanClass 实例类
         * @return          操作结果
         */
        public SerializeObject parseSerializeObjectByClass(String jsonText, Class<?> beanClass) {
            if(StringUtils.isBlank(jsonText)) {
                return null;
            }
            
            try{
                JSONObject obj = JSONObject.fromObject(jsonText);
                int status = UF.toInt(obj.get("status").toString());
                String data = UF.toString(obj.get("data").toString());
                if(status != ResultType.NORMAL || StringUtils.isBlank(data)) {
                    return parseSerializeObject(jsonText);
                }
                return new SerializeObject(status, JSONObject.toBean(JSONObject.fromObject(data), beanClass));
            } catch (Exception e) {
                getLog().error(e.getMessage());
                return null;
            }
        }
        
        /**
         * 获取Post提交返回的内容
         * @param uri       网址
         * @param timeout   超时
         * @return          网页内容
         */
        protected String getContentByPost(String uri, int timeout, Map<String, String[]> params, String sessionID) {
            String content = "";
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httpPost = new HttpPost(uri);
                log.info(uri);
    
                List<NameValuePair> nvps = new ArrayList <NameValuePair>();
    
                // 添加sessionID
                nvps.add(new BasicNameValuePair("sessionID", sessionID));
    
                Set<String> keySet = params.keySet();
                for(String key : keySet) {
                    String[] vals = params.get(key);
                    if(null == vals) continue;
                    
                    for(String v : vals) {
                        nvps.add(new BasicNameValuePair(key, v));
                    }
                }  
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, UF.getDefaultCharset()));
                
                CloseableHttpResponse response = httpclient.execute(httpPost);
                try {
                    HttpEntity httpEntity = response.getEntity();  
                    if (httpEntity != null) {
                        content = EntityUtils.toString(httpEntity);
                        log.debug(content);
                    }
                    EntityUtils.consume(httpEntity);
                } finally {
                    response.close();
                }
            }catch(Exception e){
                log.error(e.getMessage());
            } finally {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            return content;
        }
        
        /**
         * 获取参数
         * @param sessionID 登录成功后分配的Key
         * @return
         */
        public Map<String, String> getParams(String sessionID) {
            Map<String, String> params = new HashMap<String, String>();
            if(StringUtils.isNotBlank(sessionID)) {
                params.put("sessionID", sessionID);
            }
            return params;
        }
        
    
        /**
         * 构造方法
         */
        public BaseServiceImpl(Class<?> entityClass) {
            log = LogFactory.getLog(entityClass.getClass());
            this.entityClass = entityClass;
        }
        
        /**
         * 构造方法
         */
        public BaseServiceImpl(Class<?> subClass, Class<?> entityClass, String entityName) {
            log = LogFactory.getLog(subClass.getClass());
            this.entityClass = entityClass;
            this.entityName = entityName;
        }
    
        /**
         * @return the log
         */
        public final Log getLog() {
            if(null == log) {
                log = LogFactory.getLog(this.getClass());
            }
            return log;
        }
        
        @Override
        public SerializeObject find(String sessionID, Map<String, String[]> params) {
            return queryToObject(sessionID, params, entityName + ".find");
        }
    
        @Override
        public SerializeObject update(String sessionID, Map<String, String[]> params) {
            return queryToString(sessionID, params, entityName + ".update");
        }
    
        @Override
        public SerializeObject delete(String sessionID, Map<String, String[]> params) {
            return queryToString(sessionID, params, entityName + ".delete");
        }
    
        @Override
        public SerializeObject verify(String sessionID, Map<String, String[]> params) {
            return queryToString(sessionID, params, entityName + ".verify");
        }
        
        @Override
        public SerializeObject query(String sessionID, Map<String, String[]> params) {
            return queryToDataTable(sessionID, params, entityName + ".query");
        }
    
        @Override
        public SerializeObject queryToDataTable(String sessionID, Map<String, String[]> params, String key) {
            String uri = serviceUriCache.getUri(key);
            String jsonText = getContentByPost(uri, WebConfig.TIMEOUT, params, sessionID);
            
            DataTable<Object> dataTable = new DataTable<Object>();
            int status = ResultType.ERROR;
            try{
                JSONObject obj = JSONObject.fromObject(jsonText);
                status = UF.toInt(obj.get("status").toString());
                String data = UF.toString(obj.get("data").toString());
                if(status != ResultType.NORMAL) {
                    return new SerializeObject(status, data);
                }
        
                obj = JSONObject.fromObject(data);
                // 分页
                String pageString = UF.toString(obj.get("page").toString());
                if(StringUtils.isNotBlank(pageString)) {
                    dataTable.setPage((Page)JSONObject.toBean(JSONObject.fromObject(pageString), Page.class));
                }
                
                // 记录集
                String dataListString = UF.toString(obj.get("dataList").toString());
                if(StringUtils.isNotBlank(pageString)) {
                    JSONArray jsonArray = JSONArray.fromObject(dataListString);
                    dataTable.getDataList().addAll(JSONArray.toList(jsonArray, entityClass.newInstance(), new JsonConfig()));
                }
            } catch (Exception e) {
                getLog().error(e.getMessage());
                return null;
            }
            return new SerializeObject(status, dataTable);
        }
        
        public SerializeObject queryObject(String sessionID, Map<String, String[]> params,String key, Class<?> beanClass) {
            return queryToDataTableObject(sessionID, params, key, beanClass);
        }
    
        public SerializeObject queryToDataTableObject(String sessionID, Map<String, String[]> params, String key, Class<?> beanClass) {
            String uri = serviceUriCache.getUri(key);
            String jsonText = getContentByPost(uri, WebConfig.TIMEOUT, params, sessionID);
            
            DataTable<Object> dataTable = new DataTable<Object>();
            int status = ResultType.ERROR;
            try{
                JSONObject obj = JSONObject.fromObject(jsonText);
                status = UF.toInt(obj.get("status").toString());
                String data = UF.toString(obj.get("data").toString());
                if(status != ResultType.NORMAL) {
                    return new SerializeObject(status, data);
                }
        
                obj = JSONObject.fromObject(data);
                // 分页
                String pageString = UF.toString(obj.get("page").toString());
                if(StringUtils.isNotBlank(pageString)) {
                    dataTable.setPage((Page)JSONObject.toBean(JSONObject.fromObject(pageString), Page.class));
                }
                
                // 记录集
                String dataListString = UF.toString(obj.get("dataList").toString());
                if(StringUtils.isNotBlank(pageString)) {
                    JSONArray jsonArray = JSONArray.fromObject(dataListString);
                    dataTable.getDataList().addAll(JSONArray.toList(jsonArray, beanClass.newInstance(), new JsonConfig()));
                }
            } catch (Exception e) {
                getLog().error(e.getMessage());
                e.printStackTrace();
                return null;
            }
            return new SerializeObject(status, dataTable);
        }
    
        @Override
        public SerializeObject queryToString(String sessionID, Map<String, String[]> params, String key) {
            String uri = serviceUriCache.getUri(key);
            String jsonText = getContentByPost(uri, WebConfig.TIMEOUT, params, sessionID);
            return parseSerializeObject(jsonText);
        }
    
        @Override
        public SerializeObject queryToObject(String sessionID, Map<String, String[]> params, String key) {
            String uri = serviceUriCache.getUri(key);
            String jsonText = getContentByPost(uri, WebConfig.TIMEOUT, params, sessionID);
            return parseSerializeObjectByClass(jsonText, entityClass);
        }
        
        @Override
        public SerializeObject queryToList(String sessionID, Map<String, String[]> params, String key) {
            String uri = serviceUriCache.getUri(key);
            String jsonText = getContentByPost(uri, WebConfig.TIMEOUT, params, sessionID);
            
            try{
                JSONObject obj = JSONObject.fromObject(jsonText);
                int status = UF.toInt(obj.get("status").toString());
                String data = UF.toString(obj.get("data").toString());
                if(status != ResultType.NORMAL || StringUtils.isBlank(data)) {
                    return parseSerializeObject(jsonText);
                }
                
                JSONArray jsonArray = JSONArray.fromObject(data);
                List dataList = JSONArray.toList(jsonArray, entityClass.newInstance(), new JsonConfig());
                return new SerializeObject(status, dataList);
            } catch (Exception e) {
                getLog().error(e.getMessage());
                return null;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java 对http网络请求的基础封装

          本文链接:https://www.haomeiwen.com/subject/crwntxtx.html