Soap请求通过反射和泛型转java对象


import common.model.SoapUserBaen;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description : TODO
 * @Author :
 * @Date : 2022/8/1 11:21
 * @Version : 1.0
 **/
public class SoapUtil {

    public static String INVOICE_WS_URL = "http://********/services";

    /**
     * 访问webService接口
     * @param urlStr
     * @param content
     * @return
     * @throws Exception
     */
    public static StringBuffer webService(String urlStr, String content) throws Exception {
        //拼接请求报文
        String sendMsg = content;
        // 开启HTTP连接ַ
        InputStreamReader isr = null;
        BufferedReader inReader = null;
        StringBuffer result = null;
        OutputStream outObject = null;
        try {
            URL url = new URL(urlStr);
            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;

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

    }

    /**
     * XML格式字符串转相应的对象列表
     * @param result
     * @return
     * @throws Exception
     */
    public static List<SoapUserBaen> getXMLStringValue(String result) throws Exception {
        StringReader sr = new StringReader(result);     // result数据源:XML格式字符串
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        org.w3c.dom.Document document = null;
        try {
            document = builder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // soap:Envelope
        Element rootElement = document.getDocumentElement();
        // soap:Body
        Node firstChild = rootElement.getFirstChild();
        // <ns1:getHrmUserInfoResponse
        Node firstChild1 = firstChild.getFirstChild();
        // ns1:out
        Node firstChild2 = firstChild1.getFirstChild();
        // ns2:UserBeanList
        NodeList nodes = firstChild2.getChildNodes();
        List<SoapUserBaen> beanObj = getBeanObj(SoapUserBaen.class, nodes);

        return beanObj;
    }

    /**
     * 将nodeList转换为对应的类列表
     * @param classType
     * @param nodes
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> getBeanObj (Class classType, NodeList nodes) throws Exception {
        List<T> result=new ArrayList<T>();
        Field[] fields = classType.getDeclaredFields();
        Map<String,Field> fieldMap=new HashMap<>();
        for (Field field:fields){
            field.setAccessible(true);
            fieldMap.put(field.getName(),field);
        }
        if(nodes==null)return result;
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            T obj = (T) classType.newInstance();
            // 属性标签
            NodeList nodeList = node.getChildNodes();
            if (nodeList == null) continue;
            for (int j = 0; j < nodeList.getLength(); j++) {
                Node fnode = nodeList.item(j);
                if(fnode instanceof Element && fieldMap.containsKey(fnode.getNodeName())){
                    Field field = fieldMap.get(fnode.getNodeName());
                    field.set(obj,stringToTarget(fnode.getTextContent(),field.getType()));
                }
            }
            result.add(obj);
        }
        return result;
    }

    /**
     * 根据字段类型将字符串转换为对应的值
     * @param string
     * @param t
     * @return
     * @throws Exception
     */
    public static Object stringToTarget(String string, Class<?> t) throws Exception {
        boolean nullOrEmpty = StringUtils.isEmpty(string);

        if (double.class.equals(t)) {
            return nullOrEmpty ? 0 : Double.parseDouble(string);
        } else if (long.class.equals(t)) {
            return nullOrEmpty ? 0 : Long.parseLong(string);
        } else if (int.class.equals(t)) {
            return nullOrEmpty ? 0 : Integer.parseInt(string);
        } else if (float.class.equals(t)) {
            return nullOrEmpty ? 0 : Float.parseFloat(string);
        } else if (short.class.equals(t)) {
            return nullOrEmpty ? 0 : Short.parseShort(string);
        } else if (boolean.class.equals(t)) {
            return nullOrEmpty ? 0 : Boolean.parseBoolean(string);
        }  else if (Number.class.isAssignableFrom(t)) {
            return t.getConstructor(String.class).newInstance(nullOrEmpty?"0":string);
        }    else {
            return nullOrEmpty ? "" : t.getConstructor(String.class).newInstance(string);
        }
    }

    /**
     * 用于测试的请求参数
     * @return
     */
    private static String appendTestXmlContext() {
        // 构建请求报文

        StringBuffer stringBuffer = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:CUSTOMATTR=\"http://webservice.hrm.weaver/\">\n" +
                "    <SOAP-ENV:Body>\n" +
                "        <CUSTOMATTR:getHrmUserInfo>\n" +
                "            <in0></in0>\n" +
                "            <in1></in1>\n" +
                "            <in2></in2>\n" +
                "            <in3></in3>\n" +
                "            <in4></in4>\n" +
                "            <in5></in5>\n" +
                "        </CUSTOMATTR:getHrmUserInfo>\n" +
                "    </SOAP-ENV:Body>\n" +
                "</SOAP-ENV:Envelope>");
        return stringBuffer.toString();
    }


    public static void main(String[] args){
        try {
            String content=appendTestXmlContext();
            StringBuffer stringBuffer = webService(INVOICE_WS_URL, content);
            //处理返回数据
            String xmlResult = stringBuffer.toString().replace("<", "<");
            List<SoapUserBaen> xmlStringValue = getXMLStringValue(xmlResult);
            System.out.println(xmlStringValue);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


import java.io.Serializable;

/**
 * @Description : TODO
 * @Author : 
 * @Date : 2022/8/1 11:48
 * @Version : 1.0
 **/
public class SoapUserBaen implements Serializable {
    private Integer departmentid;
    private String createdate;
    private String departmentname;
    private String folk;
    private String lastname;

    public Integer getDepartmentid() {
        return departmentid;
    }

    public void setDepartmentid(Integer departmentid) {
        this.departmentid = departmentid;
    }

    public String getCreatedate() {
        return createdate;
    }

    public void setCreatedate(String createdate) {
        this.createdate = createdate;
    }

    public String getDepartmentname() {
        return departmentname;
    }

    public void setDepartmentname(String departmentname) {
        this.departmentname = departmentname;
    }

    public String getFolk() {
        return folk;
    }

    public void setFolk(String folk) {
        this.folk = folk;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

 

posted @ 2022-08-01 14:01  扰扰  阅读(352)  评论(0编辑  收藏  举报