欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java调用soap接口协议

程序员文章站 2022-10-04 08:13:35
package com.tdx.smg.service;import com.tdx.annotation.Param;import com.tdx.model.TDataResult;import com.tdx.smg.utils.SendUtils;import com.tdx.tdxUtils.TdxComUtils;import com.tdx.web.annotation.Comment;import com.tdx.web.annotation.Service;import ....
package com.tdx.smg.service;

import com.tdx.annotation.Param;
import com.tdx.model.TDataResult;
import com.tdx.smg.utils.SendUtils;
import com.tdx.tdxUtils.TdxComUtils;
import com.tdx.web.annotation.Comment;
import com.tdx.web.annotation.Service;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.xpath.DefaultXPath;

@Service(qsid = "利信通")
public class MsgService {
    private static Logger logger = LogManager.getLogger("SMG");
    @Resource(name="ServAddr")
    private String ServAddr;
    @Resource(name="LxtMsgTemplate")
    private String LxtMsgTemplate;
    @Resource(name="ProductID")
    private String ProductID;


    @Comment(value = "sendMsgInfo",name = "发送短信验证码")
    public TDataResult sendMsgInfo(@Param("mobileNum") String mobileNum,@Param("codeLength") String codeLength){
        try{
            TDataResult tDataResult = new TDataResult();

            //生成随机验证码
            String code= RandomStringUtils.randomNumeric(Integer.valueOf(codeLength));
            //发送验证码--调用利信通接口
            String  messageContent = LxtMsgTemplate.replace("###", code);
            String resultStr = getMsgResult(mobileNum,ServAddr,messageContent,ProductID);
            if(!"0".equals(getXmlMessageByName(resultStr,"status"))){
                return TdxComUtils.getErrResult("发送验证码接口调用失败");
            }

            //生成随机盐-6位字符串
            String salt= RandomStringUtils.randomAlphabetic(6);
            //手机号+验证码+salt进行MD5加密
            String mdCode = SendUtils.createMD5(mobileNum+code+salt);
            tDataResult.addItemValue("mdCode",mdCode);
            tDataResult.addItemValue("salt",salt);
            return tDataResult;
        }catch (Exception e){
            logger.info(e.getMessage(), e);
            return TdxComUtils.getErrResult("接口调用失败");
        }
    }


    //调用webService接口获取结果
    private static String getMsgResult(String mobileNum,String servAddr,String messageContent,String productID) throws Exception {
        //拼接请求报文
        String sendMsg = appendXmlContext(mobileNum,messageContent,productID);
        // 开启HTTP连接ַ
        InputStreamReader isr = null;
        BufferedReader inReader = null;
        StringBuffer result = null;
        OutputStream outObject = null;
        try {
            URL url = new URL(servAddr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            // 设置HTTP请求相关信息
            httpConn.setRequestProperty("Content-Length",
                    String.valueOf(sendMsg.getBytes().length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            // 进行HTTP请求
            outObject = httpConn.getOutputStream();
            outObject.write(sendMsg.getBytes());

            if (200 != (httpConn.getResponseCode())) {
                throw new Exception("HTTP Request is not success, Response code is " + httpConn.getResponseCode());
            }
            // 获取HTTP响应数据
            isr = new InputStreamReader(
                    httpConn.getInputStream(), "utf-8");
            inReader = new BufferedReader(isr);
            result = new StringBuffer();
            String inputLine;
            while ((inputLine = inReader.readLine()) != null) {
                result.append(inputLine);
            }
            return result.toString();

        } catch (IOException e) {
            logger.info(e.getMessage(), e);
            throw e;
        } finally {
            // 关闭输入流
            if (inReader != null) {
                inReader.close();
            }
            if (isr != null) {
                isr.close();
            }
            // 关闭输出流
            if (outObject != null) {
                outObject.close();
            }
        }

    }


    /**
     * 构造请求报文
     * @param mobileNum  手机号
     * @param messageContent 发送消息内容
     * @param productID 产品编号
     * @return
     */
    private static String appendXmlContext(String mobileNum,String messageContent,String productID){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        Date end = c.getTime();
        String srcSendTime= format.format(end).replace(" ", "T");//当前日期

        c.add(Calendar.DATE, 1);
        Date start = c.getTime();
        String srcEndTime= format.format(start).replace(" ", "T");//当前日期+1

        String clientId = "2900";
        String userName = "zybapp";
        String password = "GD1234@ebscn";
        StringBuffer stringBuffer = new StringBuffer(

                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.coagentws.techcenter.com/\">\n" +
                        "  <soapenv:Header/>\n" +
                        "  <soapenv:Body>\n" +
                        "  <ser:SmsRequest>\n" +
                        "  <smsHead>\n" +
                        "    <clientId>" + clientId + "</clientId>\n" +
                        "    <userName>" + userName + "</userName>\n" +
                        "    <password>" + password + "</password>\n" +
                        "  </smsHead>\n" +
                        "  <smsBody>\n" +
                        "    <srcSequenceId>"+"16601546581645"+"</srcSequenceId>\n" + //唯一序列号
                        "    <srcNumber>" +""+"</srcNumber>\n" + //下发的源号码
                        "    <messageType>" + "0" + "</messageType>\n" + //消息的下发类型
                        "    <messagePriority>" + "1" + "</messagePriority>\n" + //消息的优先级
                        "    <reportType>" + "1" + "</reportType>\n" + //是否需要状态报告
                        "    <messageFormat>" + "32" + "</messageFormat>\n" + //消息的编码格式
                        "    <linkID>" + "0" + "</linkID>\n" + //下行临时订购关系
                        "    <channelID>" + "0" + "</channelID>\n" + //渠道编号(默认填写 0)
                        "    <sendGroupID>" + "0" + "</sendGroupID>\n" + //下发批次(默认填写 0)
                        "    <productID>" + productID + "</productID>\n" + //产品编号
                        "    <reserve>" + "0" + "</reserve>\n" +
                        "    <destMobile>" + mobileNum + "</destMobile>\n" + //目的手机号
                        "    <messageContent>" + messageContent + "</messageContent>\n" +  //发送消息内容
                        "    <srcSendTime>" + srcSendTime + "</srcSendTime>\n" +  //系统要求下发时间(默认为当前时间)
                        "    <srcEndTime>" + srcEndTime + "</srcEndTime>\n" +  //系统要求结束时间(默认为当前时间+1天)
                        "  </smsBody>\n" +
                        "    </ser:SmsRequest>\n" +
                        "  </soapenv:Body>\n" +
                        "</soapenv:Envelope>");
        return stringBuffer.toString();

    }

    //解析返回的报文
    private static String getXmlMessageByName(String xmlResult, String nodeName) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlResult);
        DefaultXPath xPath = new DefaultXPath("//" + nodeName);
        xPath.setNamespaceURIs(Collections.singletonMap("ns2", "http://cn.gov.chinatax.gt3nf.nfzcpt.service/"));
        List list = xPath.selectNodes(doc);
        if (!list.isEmpty() && list.size() > 0) {
            Element node = (Element) list.get(0);
            return node.getText();
        }
        return "";
    }


}

本文地址:https://blog.csdn.net/m0_37914467/article/details/107359564