Java parses the data returned by calling the WebService interface through Soap, and maps it to the corresponding entity for final storage

Requirements: Call the xml string returned by the WebService interface through Soap, and the customer requests to store the returned information in the database, and finally display it on the web.
Ideas: 1. Create the corresponding entity class. The purpose is to map the useful information in the returned information to the entity class. The attributes of the entity class should be consistent with the useful information fields in the xml; 2: Use RestTemplate to send the request, set the request header parameters and the corresponding WebService interface address, and request data; 3. Use dom4j to parse the returned xml string; 4. Implement the storage operation.
Concrete implementation:
1 Create an entity class

/**
 * @Description: saop映射实体类
 * @Title: XxVo
 * @Package com.example.entity
 * @Author: ytsj
 * @CreateTime: 2023/1/16 16:43
 */
@Data
public class XxVo{
        private String asd;
        private String dfd;
        private String gfg;
        private String hgg;
}

2: Use RestTemplate to send a request to obtain the data returned by the interface. Note that the parameters of the request header are consistent with the parameters required by the interface. You can pass whatever parameters the interface needs. I also need to pass the user name and password to the interface here.

   @GetMapping("/getXmlData")
    public ResultEntity getXmlData() throws Exception {
        String url = " ";// WebService接口地址
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType("text/xml;charset=utf-8"); // 设置Content-Type
        headers.add("Accept-Encoding", "gzip, deflate, br");//设置Accept-Encoding
        // 请求头需要传递用户名和密码
        headers.add("password", "");
        headers.add("username", "");
        //这里是发生请求时body中的raw类型为xml的参数,使用StringBuffer进行拼接
        StringBuffer xmlParam = new StringBuffer();
        xmlParam.append(""); 
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<>(xmlParam.toString(), headers);
        //发送数据方法
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, formEntity, String.class);
        //得到返回的数据body
        String jsonData = forEntity.getBody();
        //组织返回的数据
        List<XxVo>  vos = getChildResult(jsonData);
        return ResultEntity.ok(vos);
    }

The type of raw in the body is
insert image description here
the data returned by xml
insert image description here

3: Parse the returned data

 /**
     * @description 通过递归调用组织的数据
     * @methodName getChildResult
     * @param [jsonData]
     * @return java.util.List<com.example.XxVo>
     * @date: 2023/1/18 11:17
     * @author ytsj
     */
    public static List<XxVo> getChildResult(String jsonData) throws UnsupportedEncodingException, DocumentException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new ByteArrayInputStream(jsonData.getBytes("UTF-8")));
        XxVo vo = new XxVo();
        Element rootElement = document.getRootElement();// 根节点
        List arrayList = new ArrayList<>();
        List<XxVo> childElement = getChildElement(rootElement, XxVo.class, vo , arrayList);
        return childElement;
    }

    /**
     * @param [elem, clazz, t, list]
     * @return java.util.List<T>
     * @description 递归遍历子节点
     * @methodName getChildElement
     * @date: 2023/1/18 10:09
     * @author ytsj
     */
    private static <T> List<T> getChildElement(Element elem, Class clazz, T t, List<T> list) throws InstantiationException, IllegalAccessException, NoSuchMethodException {
        List<Element> elems = elem.elements();
        for (Element ele : elems) {
            if (ele.getName().equals("item")) {
                List<Element> content = ele.content();
                t = (T) clazz.newInstance();
                for (Element element : content) {
                    // 通过反射获取该类的所有属性
                    Field[] fields = clazz.getDeclaredFields();
                    for (int x = 0; x < fields.length; x++) {
                        Field field = fields[x]; //获取该类的属性
                        if (field.getName().equals(element.getName())) {
                            field.setAccessible(true); // 设置属性可访问的
                            field.set(t, element.getText());
                            break;
                        }
                    }
                    list.add(t);
                }
            }
            if (ele.elements().size() > 0) { // 说明还存在子节点,继续遍历
                getChildElement(ele, clazz, t, list);
            }
        }
        return list;
    }

There is another way, which is a slight change based on the above method, which may be better understood, and I personally think so. Haha~


    /**
     * @return java.util.List<com.example.XxVo>
     * @description 递归调用
     * @methodName getChildResult
     * @date: 2023/1/17 16:07
     * @author ytsj
     */
    public List<XxVo> getChildResult(String xmlStr) {
        SAXReader sax = new SAXReader();
        List<XxVo> xxVos= new ArrayList<>();
        try {
            Document doc = sax.read(new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8)));
            Element root = doc.getRootElement();
            //递归遍历节点
            searchDoc(root, xxVos);
            return xxVos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 递归获取xml文件信息
     *
     * @param elem
     * @param <T>
     */
    private <T> void searchDoc(Element elem, List<XxVo> vos) {
        List<Element> elems = elem.elements();
        for (Element ele : elems) {
            if (ele.getName().equals("item")) {
                try {
                    // 创建一个新类
                    XxVo  vo = new XxVo();
                    // 获取该类的所有属性
                    Field[] fields = XxVo.class.getDeclaredFields();
                    List<Element> content = ele.content();
                    for (Element element : content) {
                        for (int i = 0; i < fields.length; i++) {
                            Field field = fields[i];
                            if (field.getName().equals(element.getName())) {
                                field.setAccessible(true);
                                field.set(vo , element.getText());
                                break;
                            }
                        }
                    }
                    vos.add(vo);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            if (ele.elements().size() > 0) {
                searchDoc(ele, vos);
            }
        }
    }

The parsed data
insert image description here
and then just store the parsed data in the database. The operation of warehousing is to write a new method, just batch insert.
This is my specific realization of this requirement. If you have a better method, please share it~.
If the above description is wrong, you are welcome to correct me. If you have any questions, you can add v 876942434.

Guess you like

Origin blog.csdn.net/fortunate_leixin/article/details/128724277