Restful风格的资源获取实现的JAVA工具类

公司内部的一个工具类实现Restful风格的资源获取


 

import com.keycenter.client.HmacClient;
 
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.CollectionUtils;

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

/**
 * Restful风格的资源获取
 */
public class RestFulUtil {

    /**logger*/
    private static final Logger       LOGGER           = LoggerFactory.getLogger(
            com.bioperation.common.util.RestFulUtil.class);

    /** json mapper */
    private static final ObjectMapper mapper = new ObjectMapper();

    private static final String       APPLICATION_JSON = "application/json";

    /**
     * buc授权key
     */
    // private static String             apiKey;

    /**
     * 秘钥信息
     */
    //private static String             secretKey;

    /**
     * buc服务
     */
    private static HmacClient         client;

    /**初始化配置*/
    static {
        //设置输入时忽略JSON字符串中存在而Java对象实际没有的属性  
        mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 执行Get请求,返回数据。
     * 
     * @param para
     * @param url
     * @param connectTimeOut http连接超时时间 , s
     * @param soTimeOut   so socket连接超时时间 s
     * @return
     */
    public static String executeBucGet(Map<String, String> para, String url,
                                       Integer connectTimeOut, Integer soTimeOut, String apiKey,
                                       String secretKey) {
        try {
            client = new HmacClient(apiKey, secretKey, Version.V1);
            LoggerUtil.info(LOGGER, "Initialization BUC connection success");
        } catch (Exception e) {
            LOGGER.fatal("Initialize the buc connection fails", e);
        }

        try {
            String params = com.buc.keycenter.common.util.HttpClientUtils
                .encodeParams(para);
            String reqUrl = url + "?" + params;
            String result = client.get(reqUrl);
            LoggerUtil.debug(LOGGER, "【 Call BUC】execute buc get call:reqUrl:" + reqUrl + ",result:"
                                  + result);

            return result;
        } catch (Exception e) {
            LOGGER.error("【Call BUC】Perform buc call fails", e);
            return null;
        }
    }

    /**
     * 执行Post restful资源请求
     * 
     * @param <T>
     * @param c
     * @param para
     * @param url
     * @return
     */
    public static <T> T executeBucGet(Class<T> c, Map<String, String> para, String url,
                                      String apiKey, String secretKey) {

        String body = executeBucGet(para, url, 18, 15, apiKey, secretKey);
        if (body == null || body.length() < 1) {
            return null;
        }
        //执行http访问
        try {
            T jsonToObject = jsonToObject(body, c);
            LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");

            return jsonToObject;
        } catch (Exception e) {
            LOGGER.error("Access 【" + url + "】to get data exception, result=" + body, e);
        }

        return null;
    }

    /**
     * 执行Post restful资源请求
     * 
     * @param <T>
     * @param c
     * @param para
     * @param url
     * @param connectTimeOut 超时时间
     * @return
     */
    public static <T> T executeBucGet(Class<T> c, Map<String, String> para, String url,
                                      Integer connectTimeOut, String apiKey, String secretKey) {

        String body = executeBucGet(para, url, connectTimeOut, connectTimeOut, apiKey, secretKey);
        LoggerUtil.info(LOGGER, "请求buc返回结果:", body);
        if (body == null || body.length() < 1) {
            return null;
        }
        //执行http访问
        try {
            T jsonToObject = jsonToObject(body, c);
            LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");

            return jsonToObject;
        } catch (Exception e) {
            LOGGER.error("Access 【" + url + "】to get data exception, result=" + body, e);
        }

        return null;
    }

    public static <T> T executeBucPost(Class<T> c, Map<String, String> para, String url,
                                       String apiKey, String secretKey) {
        try {
            client = new HmacClient(apiKey, secretKey, Version.V1);
            LoggerUtil.info(LOGGER, "Initialization BUC connection success");
        } catch (Exception e) {
            LOGGER.fatal("Initialize the buc connection fails", e);
        }
        //执行http访问
        try {
            String body = client.post(url, ClassCastUtils.castMapStringToMapList(para));
            LoggerUtil.info(LOGGER,"POST BUC Result:", body);
            if (StringUtil.isNotBlank(body)) {
                if (StringUtil.contains(body, "null")) {
                    body = StringUtil.replace(body, "null", "\\\"\\\"");
                }
                LoggerUtil.info(LOGGER, "According to the【" + url + "】get http return data【" + body
                                     + "】 success");

                T jsonToObject = jsonToObject(body, c);
                LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");

                return jsonToObject;
            } else {
                LOGGER.error("From 【" + url + "】get http return data is null ");
                return null;
            }
        } catch (Exception ex) {
            LOGGER.error("Access 【" + url + "】exception", ex);
        }
        return null;
    }

    /**
     * 执行Get restful资源请求
     * 
     * @param <T>
     * @param c
     * @param para
     * @param url
     * @return
     */
    public static <T> T executeGet(Class<T> c, Map<String, ?> para, String url,Map<String,String> requestHeaders) {
        HttpClient httpClient = new HttpClient();
        //默认超时时间设置为8s
        httpClient.getParams().setConnectionManagerTimeout(8000);
        httpClient.getParams().setSoTimeout(5000);
        HttpMethod httpMethod = new GetMethod(url);

        //设置查询参数
        if (!CollectionUtils.isEmpty(para)) {
            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            Set<Entry<String, ?>> entrySet = (Set) para.entrySet();
            for (Entry<String, ?> entry : entrySet) {
                String val = entry.getValue() == null ? null : entry.getValue().toString();
                paras.add(new NameValuePair(entry.getKey(), val));
            }
            httpMethod.setQueryString(paras.toArray(new NameValuePair[paras.size()]));
        }
        //设置请求头
        if (!CollectionUtils.isEmpty(requestHeaders)) {
            Set<Entry<String, String>> entrySet = (Set) requestHeaders.entrySet();
            for (Entry<String, String> entry : entrySet) {
                String val = entry.getValue() == null ? null : entry.getValue().toString();
                httpMethod.setRequestHeader(entry.getKey(),val);

            }
        }
        //执行http访问
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Execute http get request, url" + url + ", para: " + para);
            }
            int returnCode = httpClient.executeMethod(httpMethod);
            if (returnCode == HttpStatus.SC_OK) {
                String body = httpMethod.getResponseBodyAsString();
                if (StringUtil.isBlank(body)) {
                    LOGGER.error("can not get data from url:" + url);
                    return null;
                }

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("get data body from url : " + url + ", response body:" + body);
                }
                T jsonToObject = jsonToObject(body, c);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("convert body to object: " + jsonToObject);
                }

                return jsonToObject;
            } else {
                LOGGER.error("request error, url:" + url + ", code=" + returnCode);
            }
        } catch (HttpException e) {
            LOGGER.error("request error, " + url + ", client exception", e);
        } catch (IOException e) {
            LOGGER.error("request error, " + url + ", IO exception", e);
        } catch (Exception e) {
            LOGGER.error("request error, " + url + ", get data error", e);
        }

        return null;
    }

    /**
     * 执行rest的post请求
     * 
     * @param c
     * @param para
     * @param url
     * @return
     */
    public static <T> T executePost(Class<T> c, Map<String, ?> para, String url,
                                    Map<String, ?> jsonPostPara,Map<String,String> requestHeaders) {
        HttpClient httpClient = new HttpClient();
        //默认超时时间设置为8s
        httpClient.getParams().setConnectionManagerTimeout(8000);
        httpClient.getParams().setSoTimeout(5000);
        PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        //执行json的post参数封装
        if (!CollectionUtils.isEmpty(jsonPostPara)) {
            post.setRequestHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
            try {
                String postJsonStr = JSONObject.fromObject(jsonPostPara).toString();
                RequestEntity se = new StringRequestEntity(postJsonStr, APPLICATION_JSON, "utf-8");
                post.setRequestEntity(se);
            } catch (Exception e) {
                LOGGER.error("execute post json failed, params:" + jsonPostPara);
            }
        }
        //设置请求头
        if (!CollectionUtils.isEmpty(requestHeaders)) {
            Set<Entry<String, String>> entrySet = (Set) requestHeaders.entrySet();
            for (Entry<String, String> entry : entrySet) {
                String val = entry.getValue() == null ? null : entry.getValue().toString();
                post.setRequestHeader(entry.getKey(),val);

            }
        }
        //设置post参数
        if (!CollectionUtils.isEmpty(para)) {
            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            Set<Entry<String, ?>> entrySet = (Set) para.entrySet();
            for (Entry<String, ?> entry : entrySet) {
                String val = entry.getValue() == null ? null : entry.getValue().toString();
                paras.add(new NameValuePair(entry.getKey(), val));
            }
            post.setRequestBody(paras.toArray(new NameValuePair[paras.size()]));
        }
        //执行http访问
        try {
            int returnCode = httpClient.executeMethod(post);
            if (returnCode == HttpStatus.SC_OK) {
                String body = post.getResponseBodyAsString();
                if (StringUtil.isBlank(body)) {
                    LOGGER.error("get empty body from url:" + url);
                    return null;
                }
                if (StringUtil.contains(body, "null")) {
                    body = StringUtil.replace(body, "null", "\\\"\\\"");
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("get body from url:" + url + ", body:" + body);
                }

                T jsonToObject = jsonToObject(body, c);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER
                        .info("convert body to object, body:" + body + ", object:" + jsonToObject);
                }

                return jsonToObject;
            } else {
                LOGGER.error("unkown status from url:" + url + ", status:" + returnCode);
            }
        } catch (Exception ex) {
            LOGGER.error("request error url:" + url, ex);
        }
        return null;
    }

    /**
     * 执行rest的put请求
     * @param c
     * @param url
     * @return
     */
    public static <T> T executePut(Class<T> c, String url, Map<String, ?> jsonPutPara, Map<String, String> requestHeaders) {
        HttpClient httpClient = new HttpClient();
        //默认超时时间设置为8s
        httpClient.getParams().setConnectionManagerTimeout(8000);
        httpClient.getParams().setSoTimeout(5000);
        PutMethod put = new PutMethod(url);
        put.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        //执行json的post参数封装
        if (!CollectionUtils.isEmpty(jsonPutPara)) {
            put.setRequestHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
            try {
                String postJsonStr = JSONObject.fromObject(jsonPutPara).toString();
                RequestEntity se = new StringRequestEntity(postJsonStr, APPLICATION_JSON, "utf-8");
                put.setRequestEntity(se);
            } catch (Exception e) {
                LOGGER.error("executePut execute put json failed, params:" + jsonPutPara);
            }
        }
        //设置请求头
        if (!CollectionUtils.isEmpty(requestHeaders)) {
            Set<Entry<String, String>> entrySet = (Set) requestHeaders.entrySet();
            for (Entry<String, String> entry : entrySet) {
                String val = entry.getValue() == null ? null : entry.getValue().toString();
                put.setRequestHeader(entry.getKey(), val);
            }
        }
        //执行http访问
        try {
            int returnCode = httpClient.executeMethod(put);
            String body = put.getResponseBodyAsString();
            if (returnCode == HttpStatus.SC_OK) {
                if (StringUtil.isBlank(body)) {
                    LOGGER.error("executePut get empty body from url:" + url);
                    return null;
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("executePut get body from url:" + url + ", body:" + body);
                }
                T jsonToObject = jsonToObject(body, c);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER
                            .info("executePut convert body to object, body:" + body + ", object:" + jsonToObject);
                }
                return jsonToObject;
            } else {
                LOGGER.error("executePut unkown status from url:" + url + ", status:" + returnCode + "responseBody = " + body);
            }
        } catch (Exception ex) {
            LOGGER.error("executePut request error url:" + url, ex);
        }
        return null;
    }

    /**
     * 从json格式反序列化回java object对象
     * 
     * @param jsonStr
     * @param clazz
     * @return <T>
     * @throws IOException 
     * @throws JsonMappingException
     * @throws JsonParseException 
     */
    private static <T> T jsonToObject(String jsonStr, Class<T> clazz) throws Exception {
        if (String.class.equals(clazz)) {
            return (T) jsonStr;
        }
        return mapper.readValue(jsonStr, clazz);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道阻且长-行则将至-行而不辍-未来可期

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值