http方法调用

/*
 * Baidu.com Inc. 
 * Copyright (c) 2015 All Rights Reserved. 
 */

package ***

import *****

/**
 * 发起外部请求的 util
 */
public class HttpRequestUtil {
    private static Logger logger = Logger.getLogger(HttpRequestUtil.class);

    public static final String UTF8 = "UTF-8";
    public static Gson gson = new Gson();

    /**
     * 发送 get 请求
     * 
     * @param url
     *            为请求的url;
     * @param cookies
     *            :请求的参数cookies值;
     * @param tag
     *            :请求标识,若为REQUEST_TYPE_HEAD表示要根据head信息更新并返回cookies值
     * @return String类型,表示请求返回结果
     */
    public static String sendGet(String url) {
        // 定义初始化返回值
        String responseStr = "";
        // 初始化client和method
        HttpClient httpClient = new HttpClient();
        GetMethod httpGet = new GetMethod(url);
        httpGet.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8);
        try {
            // 发送请求
            httpClient.executeMethod(httpGet);
            responseStr = httpGet.getResponseBodyAsString();
        } catch (HttpException e) {
            logger.error("HttpException error (get)", e);
        } catch (IOException e) {
            logger.error("IOException error (get)", e);
        } finally {
            // 请求发送结束,关闭连接
            httpGet.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }

        // 返回请求结果
        return responseStr;
    }

    /**
     * 发送 post 请求
     * 
     * @param url
     *            get 请求的url;
     * @param cookies
     *            请求的参数cookies值;
     * @param params
     *            请求参数值
     * @return post请求返回结果
     */
    public static String sendPost(String url, Map<String, Object> params) {
        // 定义初始化返回值
        StringBuilder response = new StringBuilder();
        ;
        // 初始化client和method
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        // 设置请求参数
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8);
        // 设置 post请求的参数
        Iterator it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            postMethod.addParameter(entry.getKey().toString(), entry.getValue().toString());
        }
        try {
            // 发送请求
            httpClient.executeMethod(postMethod);
            // 获取返回结果
            InputStream is = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    response.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (HttpException e) {
            logger.error("HttpException error (post)", e);
        } catch (IOException e) {
            logger.error("IOException error (post)", e);
        } finally {
            // 请求发送结束,关闭连接
            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }

        // 返回请求结果
        return response.toString();
    }

    /**
     * 使用post请求发送json请求数据
     * 
     * @param url
     * @param params
     * @return
     */
    public static String sendPostWithParaIsjson(String url, Map<String, Object> params) {
        // 定义初始化返回值
        String responses = "";
        // 初始化client和method
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            if (MapUtils.isNotEmpty(params)) {
                String paramsStr = generateJsonParams(params);
                RequestEntity requestEntity = new StringRequestEntity(paramsStr, "text/xml", "utf-8");
                postMethod.setRequestEntity(requestEntity);
            }
            postMethod.releaseConnection();
            httpClient.executeMethod(postMethod);
            responses = postMethod.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("function :sendPostWithParaIsjson() appear error,the cause is ===>"
                    + ExceptionUtils.getFullStackTrace(e));
        }
        // 返回请求结果
        return responses;
    }

    /**
     * 使用post请求发送json请求数据
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendPostByJsonType(String url, Object params) {
        // 定义初始化返回值
        String responses = "";
        // 初始化client和method
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            if (params != null) {
                String jsonStr = gson.toJson(params);
                RequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "utf-8");
                postMethod.setRequestEntity(requestEntity);
            }
            postMethod.releaseConnection();
            httpClient.executeMethod(postMethod);
            responses = postMethod.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("function :sendPostWithParaIsjson() appear error,the cause is ===>"
                    + ExceptionUtils.getFullStackTrace(e));
        }
        // 返回请求结果
        return responses;
    }

    /**
     * 转化map内容为json串
     * 
     * @param params
     * @return
     */
    private static String generateJsonParams(Map<String, Object> paramsMap) {
        if (MapUtils.isEmpty(paramsMap)) {
            return "";
        }
        return gson.toJson(paramsMap);
    }

    /**
     * 发送 post 请求
     * 
     * @param String
     *            待解析的json字符串;
     * @return 解析后的数据 调用方式: Cookies cookies = new Cookies(); cookies =
     *         HttpRequestUtil.fromJsonToClassType( new TypeToken<Cookies>() {
     *         }.getType(), resStr);
     */
    public static <T> T fromJsonToClassType(Type type, String json) {
        // 如果json为空,则返回null
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            try {
                return gson.fromJson(json, (Type) type);
            } catch (Exception e) {
                logger.error("json " + json + " 转类 " + type + " 过程中出错~~~");
                return null; // 类型转换过程中若初问题,则返回null
            }
        }
    }
    
    /**
     * 使用jackson 反序列化java对象
     * @param classType
     * @param Json
     * @return
     */
    public static <T> T fromJsonToObject(Class<T> classType,String Json){
        T t = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            t = classType.newInstance();
            t = mapper.readValue(Json, classType);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
           throw new RuntimeException("when fromJsonToObject occur error class为"+classType+":json 为"+Json); 
        }
        return t;
    }
}
 
 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值