webservice不生成代碼的兩種調用方式

       java調用webservice接口時通常情況下都是使用生成代碼的形式調用。這種方式雖然開發簡單粗暴但是如果對方是單機部署且多單位使用的應該就不能滿足情況了,而且需要生成jar包加入到代碼相對臃腫。本文介紹使用RPC和document方式調用,代碼簡潔靈活。直接上代代碼示例:

     示例一:RPC

public String getData(String method){
    String result = "";
    try {
        // 使用RPC方式調用WebService
        RPCServiceClient serviceClient = new RPCServiceClient();
        String url = "http://xxxx/services/ldapService?wsdl"; //調用地址
        EndpointReference targetEPR = new EndpointReference(url);
        Options options = serviceClient.getOptions();
        options.setTo(targetEPR);
        options.setAction("http://gwjh.zjportal.net/invoke");
        String reqXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><invoke type=\"" + method + "\">"  //ldapSync
                + "<caller><sysid>"+unifiedPortalConfig.getGwjhSysId()+"</sysid><token>"+unifiedPortalConfig.getGwjhToken()+"</token><orgCode>"+unifiedPortalConfig.getGetGwjhOrgCode()+"</orgCode></caller><callbody>"
                + "<area>XXX\\XXX</area></callbody></invoke>";  //拼接參數
        Object[] parameters = new Object[] {reqXml};

        QName qname = new QName("http://xxxx.xxx.net/scheme/1.0", "invoke");

        // 調用方法 傳遞參數,調用服務,獲取服務返回結果集
        OMElement element = serviceClient.invokeBlocking(qname, parameters);

        result = element.getFirstElement().getText();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        return result;
    }
}

示例二:document

public void work(T_MT_Domain mt_domain){
        String domain = mt_domain.getDomain();
        try {
            String url = "http://" + domain + "/WS/NewOrgServiceOld.asmx";
            String nameSpace = "http://sxt.com.cn/";
            String methodName = "QueryAllOUInfo";

            ServiceClient serviceClient = Axis2Util.getServiceClient(url, nameSpace, methodName);

            OMFactory fac = OMAbstractFactory.getOMFactory();
            OMNamespace omNs = fac.createOMNamespace(nameSpace, "");
            OMElement method = fac.createOMElement(methodName, omNs);

            //添加參數
            Axis2Util.addInitParams(fac, omNs, method, unifiedPortalConfig.getSystemID(), unifiedPortalConfig.getAccount(), unifiedPortalConfig.getPassword());

            method.build();
            OMElement result = serviceClient.sendReceive(method);
            //判斷返回值是否存在
            if(null == result){
                return;
            }

            List<Map<String,String>> list = new ArrayList<Map<String,String>>();

            OMElement outParam = OMElementUtil.getChildOmElement(result, "outParam");
            OMElement ouInfo = OMElementUtil.getChildOmElement(outParam, "ouInfo");

            Iterator iterator2 = ouInfo.getChildElements();
            while(iterator2.hasNext()){
                OMElement threeElement = (OMElement)iterator2.next();
                if("OUInfo".equals(threeElement.getLocalName())){
                    list.add(OMElementUtil.convertToMap(threeElement.getChildElements()));
                }
            }

            //輸出獲取到的數據集合 同步數據
            List<T_HR_Organization> syncList = new ArrayList<T_HR_Organization>();
            list.stream().forEach( m -> {
                T_HR_Organization organization = new T_HR_Organization();
                organization.setSynchronizedId(m.get("ouID"));
                organization.setFullName(StringUtils.isEmpty(m.get("ouFullName")) ? m.get("ouName") : m.get("ouFullName"));
                organization.setName(m.get("ouName"));                
                organization.setSyncDomain(domain);
                syncList.add(organization);
            });

            hr_organizationService.batchSave(syncList);
            logger.info("----同步----" + domain + "-org--成功--");
        } catch (Exception axisFault) {
            axisFault.printStackTrace();
            logger.info("----同步----" + domain + "-org--失敗--");
        }
    }

參數構建工具類:

public class Axis2Util {

    /**
     * 創建service client
     * @param url
     * @param nameSpace
     * @param method
     * @return
     */
    public static ServiceClient getServiceClient(String url, String nameSpace, String method) throws Exception {
        ServiceClient serviceClient = null;
        Options options = new Options();
        EndpointReference targetEPR = new EndpointReference(url);
        options.setTo(targetEPR);
        options.setAction(nameSpace + method); //需要加上這條語句
        serviceClient = new ServiceClient();
        serviceClient.setOptions(options);
        return serviceClient;
    }

    /**
     * 構建參數
     * @param fac
     * @param omNs
     * @param method
     * @param paramKey
     * @param paramValue
     */
    public static void addParam(OMFactory fac, OMNamespace omNs, OMElement method, String paramKey, String paramValue){
        OMElement param = fac.createOMElement(paramKey, omNs);
        param.addChild(fac.createOMText(param, paramValue));
        method.addChild(param);
    }

    /**
     * 構建二級參數
     * @param fac
     * @param omNs
     * @param method
     * @param paramsKey 父參數的名稱
     * @param childParams 子參數的Key-value
     */
    public static void addChildParams(OMFactory fac, OMNamespace omNs, OMElement method, String paramsKey, Map<String, String> childParams){
        OMElement param = fac.createOMElement(paramsKey, omNs);
        for (Map.Entry<String, String> entry : childParams.entrySet()){
            OMElement childParam = fac.createOMElement(entry.getKey(), omNs);
            childParam.addChild(fac.createOMText(childParam, entry.getValue()));
            param.addChild(childParam);
        }
        method.addChild(param);
    }

    /**
     * 構建二級參數
     * @param fac
     * @param omNs
     * @param method
     * @param paramsKey
     * @param childKey
     * @param childParams
     */
    public static void addChildParams(OMFactory fac, OMNamespace omNs, OMElement method, String paramsKey, String childKey, List<String> childParams){
        OMElement param = fac.createOMElement(paramsKey, omNs);
        for (String str : childParams){
            OMElement childParam = fac.createOMElement(childKey, omNs);
            childParam.addChild(fac.createOMText(childParam, str));
            param.addChild(childParam);
        }
        method.addChild(param);
    }


    /**
     * 初始化必備參數
     * @param fac
     * @param omNs
     * @param method
     * @param systemID
     * @param account
     * @param password
     */
    public static void addInitParams(OMFactory fac, OMNamespace omNs, OMElement method, String systemID, String account, String password){
        Axis2Util.addParam(fac, omNs, method, "systemID", systemID);
        Axis2Util.addParam(fac, omNs, method, "account", account);
        Axis2Util.addParam(fac, omNs, method, "password", password);
    }
}

 

返回節點解析工具類:

public class OMElementUtil {

    /**
     * 獲取指定層級的 omElment
     * @param omElement
     * @param nodeName
     * @return
     */
    public static OMElement getChildOmElement(OMElement omElement, String nodeName){
        if(null == omElement){
            return null;
        }
        Iterator iterator = omElement.getChildElements();
        while(iterator.hasNext()){
            OMElement omElement1 = (OMElement)iterator.next();
            if(nodeName.equals(omElement1.getLocalName())){
                return omElement1;
            }
        }
        return null;
    }

    /**
     * OMElement節點轉化成Map
     * @param iterator
     * @return
     */
    public static Map<String, String> convertToMap(Iterator iterator){
        Map<String, String> map = new HashMap<String, String>();
        while (iterator.hasNext()){
            OMElement omElement1 = (OMElement) iterator.next();
            map.put(omElement1.getLocalName(), omElement1.getText());
        }
        return map;
    }
}

以上兩種方式都可用,有的webservice接口只能支持RPC方式。推薦使用document方式。如果對方的webservice接口支持http方式更好可能直接使用http方式調用。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章