httpClientWithMD5

package com.fintech.common;

import com.alibaba.fastjson.JSON;
import com.fintech.entity.CreateEnterPriseReq;
import com.fintech.entity.CreateEnterPriseResp;
import com.fintech.httputil.*;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Map;

public class HttpClientWithMD5 {
    private Logger logger = Logger.getLogger(this.getClass());

    private MD5WithRSA md5WithRSA = new MD5WithRSA();

    public boolean HttpClientReq(Object Req, String url ) throws Exception {
        boolean b;
        try {
            /**
             * 1.数据签名-私钥(.pfx)
             * 2.报文体使用数字证书进行签名
             * 3.签名原文为请求body在Json序列化后的UTF8编码得到的字节流,详情见demo示例
             * 4.将签名后得到的字节数组以base64编码方式得到的字符串值通过SignedMsg的值传递。
             * 5.HTTP-POST-UTF-8
             * 6.解密需要 公钥(.pem)
             * 7.取出报文中的SignedMsg的值
             * 8.返回json
             */

            logger.info("http-request-param:" + JSON.toJSONString(Req));

            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("Content-Type", "application/json");
            headers.put("MerId", "StandardClient");
            headers.put("SecretKey", "test123456");
            String sign = md5WithRSA.Sign(JSON.toJSONString(Req));
            headers.put("SignedMsg", sign);

            BaseHttpResponse baseHttpResponse = HttpClientUtils.httpPostRequest(url , headers, JSON.toJSONString(Req));
            String resp = baseHttpResponse.getEntityString();

            JSONObject js=JSONObject.fromObject(resp);
            String signedMsg=js.getString("SignedMsg");
            b = md5WithRSA.verify(resp, signedMsg);

            logger.info("http-response:" + resp);

        } catch (Exception e) {
            BaseResponse baseResponse = new BaseResponse();
            if (e instanceof BusinessException) {
                logger.error("http-BusinessException-异常:", e);
                baseResponse = ((BusinessException) e).getBaseResponse();
                throw new BusinessException(baseResponse);
            }
            logger.error("http异常:", e);
            baseResponse.setRecode(BusinessMsg.CALL_REMOTE_ERROR);
            baseResponse.setRemsg(BusinessMsg.getMsg(BusinessMsg.CALL_REMOTE_ERROR));
            throw new BusinessException();
        }
        return b;
    }
}
原文地址:https://www.cnblogs.com/gjack/p/10189113.html