工作中封装的三个类(HTTPClient、MD5Utils、JSONUtil)

318 阅读2分钟
@Slf4j
public class HttpUtil {
    public static final String APPJSON = "application/json";
    public static final String APPTEXT = "application/text";
    public static final String APPFORM = "application/x-www-form-urlencoded";

    public static final String UTF8 = "UTF-8";

    public static String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        return fetch(httpGet, Charset.forName(UTF8));

    }

    /**
     * 适用于 application/json|text 提交的 post
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, String params) {
        log.info("post....:url={},params= {}",url,params);

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(params, UTF8);
        entity.setContentEncoding(UTF8);
        entity.setContentType(APPTEXT);
        httpPost.setEntity(entity);

         return fetch(httpPost);
    }

    /**
     * 适用于 application/x-www-form-urlencoded 提交的 post
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String,String> params) {
        HttpPost post=new HttpPost(url);

        try{
            log.info("post....:url={},params= {}",url,stringByKey(params,"=",","));
        }catch(Exception ex){
            ex.printStackTrace();
        }

        List<NameValuePair> nvps=new ArrayList<>();
        for(String key:params.keySet()) {
            nvps.add(new BasicNameValuePair(key,params.get(key)));
        }
        post.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName(UTF8)));
        return fetch(post);
    }

    public static String fetch(HttpRequestBase httpRequest) {
        return fetch(httpRequest, Charset.forName(UTF8));
    }

    public static String fetch(HttpRequestBase httpRequest, Charset charset) {
        log.info("http url={} ", httpRequest.getURI());
        CloseableHttpClient client = HttpClients.createDefault();
        HttpResponse respContent = null;
        try {
            respContent=client.execute(httpRequest);
            HttpEntity entity = respContent.getEntity();
            String result= EntityUtils.toString(entity, charset);
            log.info("http post result={}", result);
            return result;
        }catch (Exception e){
            log.error("fetch 远程出错 url={} message={}", httpRequest.getURI(), e.getMessage());
        }
        return respContent.toString();
    }


    /**
     * 使用 Map按key进行排序得到key=value的字符串
     * @param map
     * @param eqaulsType K与V之间的拼接字符串 = 或者其他...
     * @param spliceType K-V与K-V之间的拼接字符串  & 或者|...
     * @return
     */
    public static String stringByKey(Map<String, String> map, String eqaulsType,
                                     String spliceType) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (sb.length() == 0) {
                sb.append(entry.getKey()).append(eqaulsType).append(entry.getValue());
            } else {
                sb.append(spliceType).append(entry.getKey()).append(eqaulsType)
                        .append(entry.getValue());
            }
        }

        return sb.toString();
    }
}
@Slf4j
public class JSONUtil {
    private static final JsonNodeFactory factory = JsonNodeFactory.instance;
    public static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    }

    public static  <T> T jsonToObject(String json, Class<T> clazz) {
        T t = null;
        try {
            t =  mapper.readValue(json, clazz);
        } catch (IOException e) {
             log.error("转换数据报错 json={}",json, e);
        }
        return t;
    }

    public static <T> ArrayList<T> jsonToArray(String json, Class<T> clazz) {
        ArrayList<T> list = new ArrayList<>();
        try {
            JavaType type = mapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
            list = mapper.readValue(json, type);
        } catch (IOException e) {
            log.error("转换数据报错 json={}",json, e);
        }
        return list;
    }

    public static JsonNode jsonNode(Object obj) {
        try {
            String jsonString =  mapper.writeValueAsString(obj);
            return mapper.readTree(jsonString);
        } catch (Exception e) {
            log.error("json 转换错误", e);
        }
        return null;
    }

    public static Map<String, JsonNode> jsonNodeMap(Object obj) {
        try {
            String jsonString =  mapper.writeValueAsString(obj);
            return mapper.readValue(jsonString, Map.class);
        } catch (Exception e) {
            log.error("json 转换错误", e);
        }
        return null;
    }

    public static String jsonString(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("json 转换错误", e);
        }
        return null;
    }

    public static ObjectNode objectNode() {
        return factory.objectNode();
    }
}
public class MD5Utils {

    protected static Log logger = LogFactory.getLog(MD5Utils.class);

    private static MessageDigest digest = null;

    /**
     * 字符串md5加密
     *
     * @param originalStr 原始字符串
     * @return 加密字符串
     */
    public static String encrypt(String originalStr) {
        if (originalStr == null) {
            originalStr = "";
        }
        return hash(originalStr);
    }

    /**
     * 使用Md5算法对字符串进行不可逆的哈希散列加密,并以十六进制数字字符串的形式返回结果。
     *
     * @param data 原始数据
     * @return 加密数据
     */
    public synchronized static final String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " + "Jive will be unable to function normally.");
                logger.error(nsae.getMessage());
            }
        }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }

    /**
     * 将字节数组转换为字符串
     *
     * @param bytes 字节数组
     * @return String字符串
     */
    public static final String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;
        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();
    }
}