微信小程序开发-微信支付之免密支付(自动扣费)二 小程序+java接口

接着教程1写的 一些通用的接口函数,接收解析参数等我去掉了,你们自己加,给微信传输的参数看我上一个教程中链接有解释。

1、查询签约contract_id 函数,查看签约有没有效果,签约id是什么
    private Map<String, Object> _queryContract(String openid){
        Map<String, Object> signMap = new TreeMap<>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 升序排序
                        return obj1.compareTo(obj2);
                    }
                }
        );
        signMap.put("appid",appid);
        signMap.put("mch_id",mch_id);
        signMap.put("openid",openid);
        signMap.put("plan_id",plan_id);
        signMap.put("version","1.0");
        String sign=getSign(signMap);

        StringBuilder XML = new StringBuilder();
        XML.append("<xml>");
        XML.append("<appid><![CDATA["+appid+"]]></appid>");
        XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
        XML.append("<openid><![CDATA["+openid+"]]></openid>");
        XML.append("<plan_id><![CDATA["+plan_id+"]]></plan_id>");
        XML.append("<version><![CDATA[1.0]]></version>");
        XML.append("<sign><![CDATA["+sign+"]]></sign>");
        XML.append("</xml>");
        String xml = XML.toString();
        //  调用请求微信接口函数 并return结果
        HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
        String wxResponseText = null;
        try{
            wxResponseText=httpsClientUtil.doPostXml(wxQueryContractUrl, xml);
        }catch(Exception e){
            results.put("success",false);
            results.put("msg", "_queryContract_查询签约状态请求失败");
            results.put("message", e);
            return results;
        }
        Document document = null;
        //开始解析xml字符串
        try{
            document = DocumentHelper.parseText(wxResponseText);
        }catch(Exception e){
            results.put("success",false);
            results.put("msg", "_queryContract_查询签约状态请求失败");
            results.put("message", e);
            return results;
        }
        Element root = document.getRootElement();
        Element successEl=root.element("return_code");//查询状态
        String success=successEl.getStringValue();
        if(success.equals("SUCCESS")){//此次查询成功
            Element resultCodeEL = root.element("result_code"); //业务结果
            String resultCode = resultCodeEL.getStringValue();
            if( resultCode.equals("SUCCESS") ){//判断业务结果
                //存放结果数据
                Map<String,Object> item= new HashMap<>();
                Element contractEl=root.element("contract_id");
                String contract_id=contractEl.getStringValue();
                results.put("contract_id",contract_id);
                results.put("success", true);
            }else if( resultCode.equals("FAIL") ){
                Element errCodeEl=root.element("err_code");//错误代码
                String errCode=errCodeEl.getStringValue();
                Element errCodeDesEl=root.element("err_code_des");//错误代码描述
                String errCodeDes=errCodeDesEl.getStringValue();
                results.put("success",false);
                results.put("msg",errCode);
                results.put("message", errCodeDes);
            }
        }else if(success.equals("FAIL")){
            Element msgEl=root.element("return_msg");//错误原因
            String msg=msgEl.getStringValue();
            results.put("success",false);
            results.put("msg",msg);
            results.put("message", msg);
        }
        return results;
    }
2、查询订单状态
    /查询微信订单接口selectPayOrder
    public String selectPayOrder() throws Exception {
        if(this.param==null || this.param.isEmpty()){
            try {
                this.param = getParamFromRequest();
            }catch(Exception ex){
                results.put("success", false);
                results.put("msg", "参数错误");
                results.put("message", ex.toString());
                rootLogger.error("getUserStatus--------传入参数有误!");
                rootLogger.error(ex);
                return JSON;
            }
            if( this.param==null ){
                results.put("success", false);
                results.put("msg", "参数不足");
                results.put("message", "缺失参数param");
                rootLogger.error("getUserStatus------传入参数不足,获取不到用户信息!");
                return JSON;
            }
        }
        Object param_deserialize;
        try {
            param_deserialize = JSONUtil.deserialize(this.param);
        }catch (Exception e){
            results.put("success", false);
            results.put("msg", "参数解析错误");
            results.put("message", e.getMessage());
            rootLogger.error("getUserStatus------参数解析错误!");
            rootLogger.error(e);
            return JSON;
        }

        Map<String, Object> queryMap = null;
        try {
            queryMap = (Map<String, Object>)param_deserialize;
        } catch (ClassCastException ex1) {
            results.put("success", false);
            results.put("msg", "参数解析错误");
            results.put("message", ex1.getMessage());
            rootLogger.error("getUserStatus------用户信息参数解析错误!");
            rootLogger.error(ex1);
            return JSON;
        }
        if(queryMap.get("orderNo").equals("")||queryMap.get("orderNo")==null){
            results.put("success", false);
            results.put("msg", "传入订单号为空");
            return JSON;
        }
        // ****  从传入对象中获取订单号
        String orderNo=(String) queryMap.get("orderNo");
        String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
        // **** 将所有参数组装成map排序
        Map<String, Object> signMap = new TreeMap<String, Object>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 升序排序
                        return obj1.compareTo(obj2);
                    }
                }
        );
        signMap.put("appid",appid);
        signMap.put("mch_id",mch_id);
        signMap.put("out_trade_no",orderNo);
        signMap.put("nonce_str",nonce_str);
        //调用组合签名字符串函数,获取签名结果
        String sign=getSign(signMap);
        // ****: 开始拼接xml
        StringBuilder XML = new StringBuilder();
        XML.append("<xml>");
        XML.append("<appid><![CDATA["+appid+"]]></appid>");
        XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
        XML.append("<out_trade_no><![CDATA["+orderNo+"]]></out_trade_no>");
        XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
        XML.append("<sign><![CDATA["+sign+"]]></sign>");
        XML.append("</xml>");
        String xml = XML.toString();
        // ****: 调用请求微信接口函数 并return结果
        HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
        // **** 开始调用请求微信接口
        try {
            //请求微信接口,储存结果
            String wxResponseText = httpsClientUtil.doPostXml(wxQueryOrderUrl, xml);
            //开始解析xml字符串
            Document document = DocumentHelper.parseText(wxResponseText);
            Element root = document.getRootElement();
            Element successEl=root.element("return_code");
            String success=successEl.getStringValue();
            Element msgEl=root.element("return_msg");
            String msg=msgEl.getStringValue();//getTextTrim
            //开始判断结果
            if(success.equals("SUCCESS")){//判断握手结果
                Element resultCodeEl=root.element("result_code");
                String resultCode=resultCodeEl.getStringValue();
                if( resultCode.equals("SUCCESS") ){//判断业务结果
                    Element openidEl=root.element("openid");
                    String openid=openidEl.getStringValue();
                    Element trade_stateEl=root.element("trade_state");
                    String trade_state=trade_stateEl.getStringValue();
                    Element total_feeEl=root.element("total_fee");
                    String total_fee=total_feeEl.getStringValue();
                    Element transaction_idEl=root.element("transaction_id");
                    String transaction_id=transaction_idEl.getStringValue();
                    Map<String,Object> item= new HashMap<String,Object>();
                    item.put("orderNo",orderNo);
                    item.put("openid",openid);
                    item.put("trade_state",trade_state);
                    item.put("total_fee",total_fee);
                    item.put("transaction_id",transaction_id);
                    results.put("success",true);
                    results.put("data",item);
                }else if( resultCode.equals("FAIL") ){
                    Element errCodeEl=root.element("err_code");//错误代码
                    String errCode=errCodeEl.getStringValue();
                    Element errCodeDesEl=root.element("err_code_des");//错误代码描述
                    String errCodeDes=errCodeDesEl.getStringValue();
                    results.put("success", false);
                    results.put("msg", errCodeDes);
                    results.put("message", errCode);

                }
            }else if(success.equals("FAIL")){
                results.put("success", false);
                results.put("msg", "请求微信接口出错");
                results.put("message", msg);
            }
        }catch (Exception e){
            results.put("success", false);
            results.put("msg", "请求微信接口出错");
            results.put("message", e.getMessage());
            rootLogger.error("请求微信接口出错");
            rootLogger.error(e);
        }
        return JSON;
    }
3、申请退款
    // 申请退款接口
    public String refundOrder() throws Exception{
        if(this.param==null || this.param.isEmpty()){
            this.param=getParamFromRequest();
            if( this.param==null ){
                results.put("success", false);
                results.put("msg", "参数不足");
                results.put("message", "缺失参数param");
                rootLogger.error("queryState-------缺失参数param");
                return JSON;
            }
        }
        Object param_deserialize;
        try {
            param_deserialize = JSONUtil.deserialize(param);
        }catch (Exception e){
            results.put("success", false);
            results.put("msg", "参数解析错误");
            results.put("message", e.getMessage());
            rootLogger.error("queryState-------参数解析错误!");
            rootLogger.error(e);
            return JSON;
        }

        Map<String, String> paramMap;
        try{
            paramMap = (Map<String, String>)param_deserialize;
        }catch(ClassCastException ex2){
            results.put("success", false);
            results.put("msg", "参数格式不正确");
            results.put("message", ex2.getMessage());
            rootLogger.error("queryState-------参数格式不正确!");
            rootLogger.error(ex2);
            return JSON;
        }

        //验证签名**验签方面伍勇做....

        //开始获取参数并判断
        int total_fee=Integer.parseInt( paramMap.get("amount") );//订单金额
        int refund_fee=Integer.parseInt( paramMap.get("refund_fee") );//退款金额
        String out_refund_no=paramMap.get("out_refund_no");//退款商户订单号-商户系统内部的退款单号唯一
        String transaction_id=paramMap.get("transaction_id");//微信支付订单号
        //生成随机字符串
        String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
        //下面这些是存数据库用
        String openid=paramMap.get("openid");
        String time=paramMap.get("time");
        String orderNo=paramMap.get("orderNo");
        String lineName=paramMap.get("lineName");
        String stationName=paramMap.get("stationName");
        String start_station=paramMap.get("start_station");
        String end_station=paramMap.get("end_station");
        // TODO: 签名数据源
        Map<String,Object> refundData=new TreeMap<String, Object>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 升序排序
                        return obj1.compareTo(obj2);
                    }
                });
        refundData.put("appid",appid);
        refundData.put("mch_id",mch_id);
        refundData.put("nonce_str",nonce_str);
        refundData.put("transaction_id",transaction_id);
        refundData.put("out_refund_no",out_refund_no);
        refundData.put("total_fee",total_fee);
        refundData.put("refund_fee",refund_fee);
        //调用组合签名字符串函数,获取签名结果
        String sign=getSign(refundData);

        // TODO: 开始拼接xml
        StringBuilder XML = new StringBuilder();
        XML.append("<xml>");
        XML.append("<appid><![CDATA["+appid+"]]></appid>");
        XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
        XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
        XML.append("<transaction_id><![CDATA["+transaction_id+"]]></transaction_id>");
        XML.append("<out_refund_no><![CDATA["+out_refund_no+"]]></out_refund_no>");
        XML.append("<total_fee><![CDATA["+total_fee+"]]></total_fee>");
        XML.append("<refund_fee><![CDATA["+refund_fee+"]]></refund_fee>");
        XML.append("<sign><![CDATA["+sign+"]]></sign>");
        XML.append("</xml>");
        String xml = XML.toString();
        // TODO: 调用请求微信接口函数 并return结果
        try{
            HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
            String wxResponseText= httpsClientUtil.doPostXml(wxRefundUrl, xml);
            //开始解析xml字符串
            Document document = DocumentHelper.parseText(wxResponseText);
            Element root = document.getRootElement();
            Element returnCodeEL=root.element("return_code");//握手状态
            String returnCode=returnCodeEL.getStringValue();
            Element returnMsgEl;
            String returnMsg;
            if(returnCode.equals("SUCCESS")){//判断握手结果
                //握手成功
                Element resultCodeEl=root.element("result_code");
                String resultCode=resultCodeEl.getStringValue();
                if(resultCode.equals("SUCCESS")){//判断业务结果
                    //获取结果数据
                    Element refundIdEl=root.element("refund_id");
                    String refundId=refundIdEl.getStringValue();
                    //返回给前台
                    results.put("refundId",refundId);
                    results.put("success",true);
                    //申请成功 开始储存数据库表
                    Map<String,String> saveData= new HashMap<String,String>();
                    saveData.put("transactionId",transaction_id);
                    saveData.put("total_fee",(total_fee+"") );
                    saveData.put("refund_fee",(refund_fee+"") );
                    saveData.put("out_refund_no",out_refund_no );
                    saveData.put("refund_id",refundId );
                    saveData.put("openid",openid);//
                    saveData.put("time",time);
                    saveData.put("orderNo",orderNo);
                    saveData.put("lineName",lineName );
                    saveData.put("stationName",stationName);//
                    saveData.put("start_station",start_station);
                    saveData.put("end_station",end_station);
                    //开始调用sql
                    try{
                        dbExecutor.insert("com.sutpc.dao.PayDao.saveRefundOrder",saveData);
                    }catch (Exception e){
                        rootLogger.error("doWxPay-----存储失败!");
                        rootLogger.error(e);
                    }
                }else if(resultCode.equals("FAIL")){
                    Element errCodeEl=root.element("err_code");//错误代码
                    String errCode=errCodeEl.getStringValue();
                    Element errCodeDesEl=root.element("err_code_des");//错误代码描述
                    String errCodeDes=errCodeDesEl.getStringValue();
                    results.put("success",false);
                    results.put("message",errCode);
                    results.put("msg", errCodeDes);
                }
            }else if(returnCode.equals("FAIL")){
                //握手失败
                returnMsgEl=root.element("return_msg");
                returnMsg=returnMsgEl.getStringValue();
                results.put("success",false);
                results.put("msg","请求微信失败");
                results.put("message",returnMsg);
            }
        }catch (Exception e){
            results.put("success",false);
            results.put("msg","请求微信失败");
            results.put("message","微信拒接请求,未安装证书");
        }
        return JSON;
    }
4、查询退款结果
    // 查询退款结果 wxSelectRefund
    public String selectRefund() throws Exception{
        if(this.param==null || this.param.isEmpty()){
            this.param=getParamFromRequest();
            if( this.param==null ){
                results.put("success", false);
                results.put("msg", "参数不足");
                results.put("message", "缺失参数param");
                rootLogger.error("queryState-------缺失参数param");
                return JSON;
            }
        }
        Object param_deserialize;
        try {
            param_deserialize = JSONUtil.deserialize(param);
        }catch (Exception e){
            results.put("success", false);
            results.put("msg", "参数解析错误");
            results.put("message", e.getMessage());
            rootLogger.error("queryState-------参数解析错误!");
            rootLogger.error(e);
            return JSON;
        }

        Map<String, String> paramMap;
        try{
            paramMap = (Map<String, String>)param_deserialize;
        }catch(ClassCastException ex2){
            results.put("success", false);
            results.put("msg", "参数格式不正确");
            results.put("message", ex2.getMessage());
            rootLogger.error("selectRefund-------参数格式不正确!");
            rootLogger.error(ex2);
            return JSON;
        }
        String refund_id=paramMap.get("refund_id");
        if(refund_id.equals("") || refund_id==null){
            results.put("success", false);
            results.put("msg", "参数不正确");
            results.put("message", "refund_id is null");
            rootLogger.error("selectRefund-------缺少refund_id参数!");
            return JSON;
        }
        // TODO: 签名数据源
        Map<String,Object> selectRefundData=new TreeMap<String, Object>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 升序排序
                        return obj1.compareTo(obj2);
                    }
                });
        selectRefundData.put("appid",appid);
        selectRefundData.put("mch_id",mch_id);
        selectRefundData.put("refund_id",refund_id);
        //生成随机字符串
        String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
        selectRefundData.put("nonce_str",nonce_str);
        String sign=getSign(selectRefundData);
        // TODO: 开始拼接xml
        StringBuilder XML = new StringBuilder();
        XML.append("<xml>");
        XML.append("<appid><![CDATA["+appid+"]]></appid>");
        XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
        XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
        XML.append("<refund_id><![CDATA["+refund_id+"]]></refund_id>");
        XML.append("<sign><![CDATA["+sign+"]]></sign>");
        XML.append("</xml>");
        String xml = XML.toString();
        try{
            HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
            String wxResponseText= httpsClientUtil.doPostXml(wxSelectRefund, xml);
            //开始解析xml字符串
            Document document = DocumentHelper.parseText(wxResponseText);
            Element root = document.getRootElement();
            Element returnCodeEL=root.element("return_code");//握手状态
            String returnCode=returnCodeEL.getStringValue();
            Element returnMsgEl;
            String returnMsg;
            if(returnCode.equals("SUCCESS")){//判断握手结果
                //握手成功
                Element resultCodeEl=root.element("result_code");
                String resultCode=resultCodeEl.getStringValue();
                if(resultCode.equals("SUCCESS")){//判断业务结果
                    //获取结果数据
                    Element refundStatusEl=root.element("refund_status_0");
                    String refundStatus=refundStatusEl.getStringValue();
                    Element refundRecvAccoutEl=root.element("refund_recv_accout_0");
                    String refundRecvAccout=refundRecvAccoutEl.getStringValue();
                    //返回给前台
                    results.put("refund_status",refundStatus);
                    results.put("refund_recv_accout",refundRecvAccout);
                    results.put("refund_id",refund_id);
                    results.put("success",true);
                    //申请成功 开始储存数据库表
                    Map<String,String> saveData= new HashMap<String,String>();
                    saveData.put("refund_status",refundStatus);//状态 SUCCESS—退款成功 FAIL—退款失败 PROCESSING—退款处理中 NOTSURE—未确定,需要商户原退款单号重新发起
                    saveData.put("refund_recv_accout",refundRecvAccout);//退到哪1)退回银行卡:2)退回支付用户零钱:
                    saveData.put("refund_id",refund_id);
                    //开始调用sql
                    try{
                        dbExecutor.insert("com.sutpc.dao.PayDao.updateRefundOrder",saveData);
                    }catch (Exception e){
                        rootLogger.error("doWxPay-----存储失败!");
                        rootLogger.error(e);
                    }
                }else if(resultCode.equals("FAIL")){
                    Element errCodeEl=root.element("err_code");//错误代码
                    String errCode=errCodeEl.getStringValue();
                    Element errCodeDesEl=root.element("err_code_des");//错误代码描述
                    String errCodeDes=errCodeDesEl.getStringValue();
                    results.put("success",false);
                    results.put("message",errCode);
                    results.put("msg", errCodeDes);
                    //失败 记录失败原因 开始储存数据库表
                    Map<String,String> saveData= new HashMap<String,String>();
                    saveData.put("err_code",errCode);
                    saveData.put("err_code_des",errCodeDes);
                    saveData.put("refund_id",refund_id);
                    //开始调用sql
                    try{
                        dbExecutor.update("com.sutpc.dao.PayDao.updateRefundOrder",saveData);
                    }catch (Exception e){
                        rootLogger.error("doWxPay-----存储失败!");
                        rootLogger.error(e);
                    }
                }
            }else if(returnCode.equals("FAIL")){
                //握手失败
                returnMsgEl=root.element("return_msg");
                returnMsg=returnMsgEl.getStringValue();
                results.put("success",false);
                results.put("msg","请求微信失败");
                results.put("message",returnMsg);
            }
        }catch (Exception e){
            results.put("success",false);
            results.put("msg","请求微信失败");
            results.put("message","连接微信请求失败");
        }
        return JSON;
    }
5、查询订单状态2
    // 查询订单状态接口
    public String queryOrder() throws Exception {
        if(this.param==null || this.param.isEmpty()){
            this.param=getParamFromRequest();
            if( this.param==null ){
                results.put("success", false);
                results.put("msg", "参数不足");
                results.put("message", "缺失参数param");
                rootLogger.error("queryOrder--------缺失参数param!");
                return JSON;
            }
        }
        Object param_deserialize;
        try {
            param_deserialize = JSONUtil.deserialize(param);
        }catch (Exception e){
            results.put("success", false);
            results.put("msg", "参数解析错误");
            results.put("message", e.getMessage());
            rootLogger.error("queryOrder--------参数解析错误!");
            rootLogger.error(e);
            return JSON;
        }
        Map<String, String> paramMap;
        try{
            paramMap = (Map<String, String>)param_deserialize;
        }catch(ClassCastException ex2){
            results.put("success", false);
            results.put("msg", "参数格式不正确");
            results.put("message", ex2.getMessage());
            rootLogger.error("queryOrder--------参数格式不正确!");
            rootLogger.error(ex2);
            return JSON;
        }
        //判断参数是否正确
        String out_trade_no=paramMap.get("orderNo");
        if( out_trade_no==null || out_trade_no.equals("")  ){
            results.put("success", false);
            results.put("msg", "订单号错误");
            results.put("message", "orderNo参数不存在或空");
            rootLogger.error("queryOrder--------订单号错误:orderNo参数不存在或空!");
            return JSON;
        }
        //将所有参数组装成map排序
        Map<String, Object> signMap = new TreeMap<String, Object>(
            new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 升序排序
                    return obj1.compareTo(obj2);
                }
            }
        );
        signMap.put("mch_id",mch_id);
        signMap.put("appid",appid);
        signMap.put("out_trade_no",out_trade_no);
        //生成随机字符串
        String nonce_str= MD5Utils.getNonceStr(32);
        signMap.put("nonce_str",nonce_str);
        signMap.put("sign_type","MD5");
        //获取签名结果
        String sign=getSign(signMap);
        //拼接XML
        String xml = "<xml>" +
                "<appid><![CDATA[" + appid + "]]></appid>" +
                "<mch_id><![CDATA[" + mch_id + "]]></mch_id>" +
                "<nonce_str><![CDATA[" + nonce_str + "]]></nonce_str>" +
                "<out_trade_no><![CDATA[" + out_trade_no + "]]></out_trade_no>" +
                "<sign><![CDATA[" + sign + "]]></sign>" +
                "<sign_type><![CDATA[MD5]]></sign_type>" +
                "</xml>";
        // TODO: 调用请求微信接口函数 并return结果
        HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
        String wxResponseText=httpsClientUtil.doPostXml(wxQueryOrderUrl, xml);
        //开始解析xml字符串
        Document document = DocumentHelper.parseText(wxResponseText);
        Element root = document.getRootElement();
        Element successEl=root.element("return_code");//查询状态
        String success=successEl.getStringValue();
        //开始判断结果
        if(success.equals("SUCCESS")){//判断查询状态
            Element resultCodeEL=root.element("result_code"); //业务结果
            String resultCode=resultCodeEL.getStringValue();
            if( resultCode.equals("SUCCESS") ){//判断业务结果
                //存放结果数据
                Map<String,Object> item= new HashMap<String,Object>();
                Element outTradeNoEl=root.element("out_trade_no");//商户订单号 和 其实传入的订单号一样
                String outTradeNo=outTradeNoEl.getStringValue();
                //订单目前状态 : SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 ACCEPT—已接收,等待扣款 PAY_FAIL--支付失败(其他原因,如银行返回失败)
                Element tradeStateEl=root.element("trade_state");
                String tradeState=tradeStateEl.getStringValue();
                if( tradeState.equals("SUCCESS") ){ //判断支付结果是什么
                    item.put("status", 1);
                }else{
                    item.put("status", -1);
                }
                item.put("orderId",outTradeNo);
                results.put("result",item);
                results.put("success",true);
            }else if( resultCode.equals("FAIL") ){
                Element errCodeEl=root.element("err_code");//错误代码
                String errCode=errCodeEl.getStringValue();
                Element errCodeDesEl=root.element("err_code_des");//错误代码描述
                String errCodeDes=errCodeDesEl.getStringValue();
                results.put("success",false);
                results.put("msg",errCode);
                results.put("message", errCodeDes);
                rootLogger.warn("queryOrder--------查询结果错误!");
                rootLogger.warn(errCodeDes);
            }
        }else if(success.equals("FAIL")){
            Element msgEl=root.element("return_msg");//错误原因
            String msg=msgEl.getStringValue();
            results.put("success",false);
            results.put("msg",msg);
            rootLogger.error("queryOrder--------查询失败!");
            rootLogger.error(msg);
        }
        return JSON;
    }

HttpsClientUtil 实现代码, 不过我们这个架构比较老。。

package com.sutpc.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.IOP.Encoding;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Key;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpsClientUtil {
    public String doPost(String url, Map<String,String> map) throws Exception{
        String result = null;
        HttpClient httpClient = new SSLClient();
        HttpPost httpPost = new HttpPost(url);
        //设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String,String> elem = (Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
        }
        if(list.size() > 0){
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entity);
        }
        HttpResponse response = httpClient.execute(httpPost);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }
    public String doGet(String url, Map<String,String> map) throws Exception{
        String result = null;
        HttpClient httpClient = new SSLClient();
        String param="";
        for(String nameKey:map.keySet()){
            param += nameKey+"="+map.get(nameKey)+"&";
        }
        param = param.substring(0,param.length()-1);
        String urlNameString = url + "?" + param;
        HttpGet httpGet = new HttpGet(urlNameString);
        HttpResponse response = httpClient.execute(httpGet);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }
    public String doPostXml(String url, String xml) throws Exception{
        String result = null;
        HttpClient httpClient = new SSLClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type","text/xml;charset=UTF-8");
        StringEntity stringEntity = new StringEntity(xml, "UTF-8");
        stringEntity.setContentEncoding("UTF-8");

        httpPost.setEntity(stringEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }
    public String httpPostXmlStr(String url, String xml) throws Exception{
        HttpClient httpClient = HttpClients.createDefault();
//        HttpClient httpClient = new SSLClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
        //设置参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("data", xml));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        String result = null;
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }
}

SSLClient 实现

package com.sutpc.utils;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
    public SSLClient() throws Exception{
        super();
        //传输协议需要根据自己的判断 
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容