CXF动态webservice客户端调用

时间: 2023-08-15 admin 互联网

CXF动态webservice客户端调用

CXF动态webservice客户端调用

项目中 需要调东华提供的webservice,调webservice需要加密,静态调用需要生成一堆代码,我们项目只用其中几个接口,实现体检预约等,所以选了CXF动态客户端调用webservice的方式.核心代码如下:

TJWebServiceClient.java
 public static String callWebService(String methodname, String requestCode, String quesXml){

        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf
                .createClient(".Service.NetComService.cls?wsdl=1&CacheUserName=dhuser&CachePassword=dhpassword&CacheNoRedirect=1");
        // url为调用webService的wsdl地址
        // 需要密码的情况需要加上用户名和密码
//         client.getOutInterceptors().add(new ClientLoginInterceptor("dhuser","dhuser"));
        Map<String, Object> props = new HashMap<String, Object>();
        props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
        //密码类型 明文:PasswordText密文:PasswordDigest
        props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
        //用户名
        props.put(WSHandlerConstants.USER, "dhwebservice");
        //将PasswordHandler 的类名传递给服务器,相当于传递了密码给服务器
        props.put(WSHandlerConstants.PW_CALLBACK_CLASS, PasswordHandler.class.getName());
        WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(props);
        client.getOutInterceptors().add(wssOut);
        // paramvalue为参数值:nb ,即是该方法需要提供的参数
        Object[] objects;
        try {


            objects = client.invoke(methodname, requestCode,quesXml);
            String objStr = objects[0].toString();
//            System.out.println(objStr);

            return objStr;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
    public static <T> T getWSResponseResult(String methodname,String requestCode,Object obj,Class<T> c) throws Exception {

        if(StringUtils.isBlank(methodname))
        {//默认新方法
            methodname = "RequestSubmitNew";
        }
        String requestXml = JaxbUtil.bean2Xml(obj,obj.getClass());

//        System.out.println(requestCode + " 请求报文:" + requestXml);
        String res = callWebService(methodname,requestCode,requestXml);

        T t = JaxbUtil.xml2Object(res,c);

        return t;
    }
PasswordHandler.java
public class PasswordHandler implements CallbackHandler {

    @Override
    public void handle(javax.security.auth.callback.Callback[] callbacks) {
        for (int i = 0; i < callbacks.length; i++) {
            WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
            pc.setPassword("dhpass");
        }
    }
}

调用:

    @Override
    public PackagesLevelResponseVo getPackagesLevelInfo(PackagesLevelRequestVo quesVo) {
        try {

            PackagesLevelResponseVo rsVo = TJWebServiceClient.getWSResponseResult("RequestSubmitNew", RequestCodeEnum.REQUEST_HS10201.key,quesVo,PackagesLevelResponseVo.class);
            return rsVo;

        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
       return null;
    }

JaxUtil.java

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;


public class JaxbUtil {


    /**
     * JavaBean装换成xml
     * 默认编码UTF-8
     * @param obj
     * @return
     */
    public static String converTomXml(Object obj) {
        return converToXml(obj,"UTF-8");

    }
    /**
     * JavaBean装换成xml
     * @param obj
     * @param encoding
     * @return
     */
    private static String converToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj,writer);
            result =writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * xml装换成JavaBean
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings("unchecked")
    public static<T> T converyToJavaBean(String xml,Class<T> c){
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T)unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;

    }


    /**
     * (多层)map转换为xml格式字符串
     *
     * @param map 需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     * @throws UnsupportedEncodingException
     */
    public static String multilayerMapToXml(Map<String, Object> map, boolean isCDATA) throws UnsupportedEncodingException{
        String parentName = "response";
        Document doc = DocumentHelper.createDocument();
        doc.addElement(parentName);
        String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA);
        return formatXML(xml);
    }

    /**
     * multilayerMapToXml核心方法,递归调用
     *
     * @param element 节点元素
     * @param parentName 根元素属性名
     * @param map 需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     */
    @SuppressWarnings("unchecked")
    private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCDATA) {
        Element xmlElement = element.addElement(parentName);
        map.keySet().forEach(key -> {
            Object obj = map.get(key);
            if (obj instanceof Map) {
                recursionMapToXml(xmlElement, key, (Map<String, Object>)obj, isCDATA);
            } else {
                String value = obj == null ? "" : obj.toString();
                if (isCDATA) {
                    xmlElement.addElement(key).addCDATA(value);
                } else {
                    xmlElement.addElement(key).addText(value);
                }
            }
        });
        return xmlElement.asXML();
    }

    /**
     * 格式化xml,显示为容易看的XML格式
     *
     * @param xml 需要格式化的xml字符串
     * @return
     */
    public static String formatXML(String xml) {
        String requestXML = null;
        try {
            // 拿取解析器
            SAXReader reader = new SAXReader();
            Document document = reader.read(new StringReader(xml));
            if (null != document) {
                StringWriter stringWriter = new StringWriter();
                // 格式化,每一级前的空格
                OutputFormat format = new OutputFormat("    ", true);
                // xml声明与内容是否添加空行
                format.setNewLineAfterDeclaration(false);
                // 是否设置xml声明头部
                format.setSuppressDeclaration(false);
                // 是否分行
                format.setNewlines(true);
                XMLWriter writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                writer.close();
                requestXML = stringWriter.getBuffer().toString();
            }
            return requestXML;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @param xmlStr
     * @param c
     * @return
     */
    public static <T>T xml2Object(String xmlStr, Class<T> c)
    {
        try
        {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();

            T t = (T) unmarshaller.unmarshal(new InputStreamReader(
                    new ByteArrayInputStream(xmlStr.getBytes()), Charset.forName("UTF-8")));

            return t;

        } catch (JAXBException e) {  e.printStackTrace();  return null; }

    }

    /**
     * java对象转换为xml文件
     * @param model java对象.Class
     * @return xml文件的String
     * @throws Exception
     */
    public static String bean2Xml(Object obj, Class<?> model) throws Exception {

        JAXBContext jaxbContext = JAXBContext.newInstance(model);

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 设置编码字符集
//        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出,有分行和缩进
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//		marshaller.setProperty("com.sun.xml.bind.xmlHeaders",
//				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshal(obj, baos);
        String xmlObj = new String(baos.toByteArray(),"UTF-8"); // 生成

        return xmlObj;

    }

    /**
     * json
     * String转换为xml文件
     * @param json
     * @return xml文件的 String
     * @throws Exception
     */
//    public static String json2Xml(String json){
//        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><request>";
//        try {
//            org.json.JSONObject json1 = new org.json.JSONObject(json);
//            xml += XML.toString(json1);
//            xml += "</request>";
//        }catch (Exception ex){
//            ex.getStackTrace();
//        }
//        return xml;
//
//    }

}