hutool SoapClient实现webservice接口调用

时间:2024-10-09 07:48:06
天气预报webservice url

http:///WebServices/?wsdl

package ;

import ;
import ;
import org.;
import org.;
import org.;

import ;
import ;
import ;
import ;

/**
 * Created by ylm on 2022/6/9 13:39
 * Created by Miracle Luna on 2022/6/9 13:39
 */
public class SoapClientWebService {
    public static void main(String[] args) {
        //请求地址
        String soapUrl = "/WebServices/?wsdl";
        HashMap<String, Object> map = new HashMap<>();
        ("theCityName", "武汉");
        SoapClient soapClient = (soapUrl)
                //请求方法,命名空间
                .setMethod("web:getWeatherbyCityName", "/")
                .setParams(map);
        String sendSoap = (true);
        (sendSoap);
        Map<String, String> map1 = new HashMap<String, String>();
        Map soapMap = XmlMap(sendSoap, map1);
        ((soapMap));

    }

    
1.1 将xml转换为Map。 支持xml标签多层嵌套,并以"."分隔多级标签(不包括根节点)。 不支持XML标签重复时的情况

    public static Map<String, String> XmlMap(String xml, Map<String, String> map) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = (new StringReader(xml));
            Element root = ();
            String path = "";
            if ((().trim())) {
                path = (().trim());
                (().trim());
            }
            for (Iterator i = (); (); ) {
                Element element = (Element) ();
                if (()) {
                    if (() > 0) {
                        (path + ().trim(), ());
                    } else {
                        (().trim(), ());
                    }
                } else {
                    (().trim(), path + ().trim() + ".");
                    XmlMap((), map);
                }
            }
        } catch (Exception e) {
            ();
        }
        return map;
    }

}

1.2 将返回得xml解析为字符串

//转成xml对象
Document document = (sendSoap);
//通过命名空间获取节点数据
NodeList nodeList = (namespaceURL, "*");
//取出第一个节点数据
 jsonObj = new JSONObject((0).getTextContent().trim());
Result result = new Result();
(("响应状态").toString());
(("说明").toString());

返回得sendSoap  xml

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<soap:Envelope xmlns:soap="/soap/envelope/" xmlns:xsd="http:///2001/XMLSchema" xmlns:xsi="http:///2001/XMLSchema-instance">
  <soap:Body>
    <wsCmpJnlResponse xmlns="/JeezExternalDataService">
      <wsCmpJnlResult>{"响应状态":0,"说明":"参数格式不正确","处理笔数":0,"处理明细":null}</wsCmpJnlResult>
    </wsCmpJnlResponse>
  </soap:Body>
</soap:Envelope>

控制台输出