JAVA call WSDL

package com.cjc.combemail.project.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import com.cjc.combemail.common.util.ResultUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created on 2019年06月18日 16:41.
 */
@Component
public class WsdlUtil {

    public static Map<String,Object> requestWsdl(String method, Map<String, Object> params) {
        String endpoint = "http://mail****/apiws/services/API?wsdl";
        String namespace = "http://coremail.cn/apiws";
        Map<String,Object> map = new HashMap<>();
        try {
            URL url = new URL(endpoint);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            OutputStream oStream = con.getOutputStream();
            //下面这行代码是用字符串拼出要发送的xml,xml的内容是从测试软件里拷贝出来的
            //需要注意的是,有些空格不要弄丢哦,要不然会报500错误的。
            //参数什么的,你可以封装一下方法,自动生成对应的xml脚本
            String paramStr = "";
            String soap = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                    "    <Body>" +
                    "        <" + method + " xmlns=\"" + namespace + "\">";
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                paramStr += "<" + entry.getKey() + " xmlns=\"\">" + entry.getValue() + "</" + entry.getKey() + ">";
            }
            soap += paramStr;
            soap += "        </" + method + ">" +
                    "    </Body>" +
                    "</Envelope>";
            oStream.write(soap.getBytes());
            oStream.close();

            InputStream iStream = con.getInputStream();
            Reader reader = new InputStreamReader(iStream);

            int tempChar;
            String str = new String();
            while ((tempChar = reader.read()) != -1) {
                str += (char) tempChar;
            }
            Map<String,Object> resultMap = ResultUtils.xml2map(str,false);

            //下面这行输出返回的xml到控制台,相关的解析操作大家自己动手喽。
            //如果想要简单的话,也可以用正则表达式取结果出来。
            map = (Map)((Map)((Map)resultMap.get("Body")).get(method + "Response")).get("return");
            iStream.close();
            oStream.close();
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

 

Guess you like

Origin blog.csdn.net/Amelia__Liu/article/details/93210769