webService 实战篇--客户端调用

前言

好久都没有使用webservice 进行接口联调了,今天需要一个和第三方的webservice 接口进行联调。整体是很简单的。记录一些坑。

wsdl

首先由于测试环境网络不互通,对方提供的开始提供的wsdl 死活不能解析成功,后来找他们算账,是他们提供的wsdl 文件格式有问题。
我们这里提供最终的wsdl 文件吧

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://ws.gxlu.com.cn"
    xmlns:apachesoap="http://xml.apache.org/xml-soap"
    xmlns:impl="http://ws.gxlu.com.cn"
    xmlns:intf="http://ws.gxlu.com.cn"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->
    <wsdl:types>
        <schema elementFormDefault="qualified" targetNamespace="http://ws.gxlu.com.cn"
            xmlns="http://www.w3.org/2001/XMLSchema">
            <element name="getGridResource">
                <complexType>
                    <sequence>
                        <element name="requestXml" type="xsd:string"/>
                    </sequence>
                </complexType>
            </element>
            <element name="getGridResourceResponse">
                <complexType>
                    <sequence>
                        <element name="getGridResourceReturn" type="xsd:string"/>
                    </sequence>
                </complexType>
            </element>
        </schema>
    </wsdl:types>
    <wsdl:message name="getGridResourceResponse">
        <wsdl:part element="impl:getGridResourceResponse" name="parameters"></wsdl:part>
    </wsdl:message>
    <wsdl:message name="getGridResourceRequest">
        <wsdl:part element="impl:getGridResource" name="parameters"></wsdl:part>
    </wsdl:message>
    <wsdl:portType name="GridWebService">
        <wsdl:operation name="getGridResource">
            <wsdl:input message="impl:getGridResourceRequest" name="getGridResourceRequest"></wsdl:input>
            <wsdl:output message="impl:getGridResourceResponse" name="getGridResourceResponse"></wsdl:output>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="GridWebServiceSoapBinding" type="impl:GridWebService">
        <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="getGridResource">
            <wsdlsoap:operation soapAction=""/>
            <wsdl:input name="getGridResourceRequest">
                <wsdlsoap:body use="literal"/>
            </wsdl:input>
            <wsdl:output name="getGridResourceResponse">
                <wsdlsoap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="GridWebServiceService">
        <wsdl:port binding="impl:GridWebServiceSoapBinding" name="GridWebService">
            <wsdlsoap:address location="http://10.213.54.118:7000/BundleSmart/webservice/GridWebService"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

IDEA 解析WSDL

如果右键没有发现webservice ,说明你的IDEA 没有webservice 插件,不用慌,装一个就可以了,也很简单。
ctrl+alt+s,勾选如下图两个就可以了。
在这里插入图片描述
右键项目webservice,如下图,会弹出框。
在这里插入图片描述
在这里插入图片描述
file:/D:/guanxian.wsdl 是我本地的wsdl 文件路径,如果网络互通,可以直接填写url.

com.guanxian.webserver 是我们自定义存放的包路径。
点击OK,就可以下载成功,如下图。
在这里插入图片描述

请求参数

在这之前,先说一下需求以及接口的格式吧。
在这里插入图片描述
输出格式:

<?xml version="1.0" encoding="UTF-8"?>
<responseparam>
	<content>
		<id>网格、经营部ID</id>
		<type>1-网格、2-经营部</type>
                <status>0-失败、1-成功</status>
                <notes>失败时反馈失败信息(例:该网格数据不存在、该经营部数据不存在。。。)</notes>
		<!--gcll_line记录专线信息,如果存在多条专线,则传递多个值--> 
		<gcll_line>
			<gcll_name>专线名称</gcll_name>
			<gcll_type>专线类型</gcll_type>
		</gcll_line>
		<gcll_line>
			<gcll_name>专线名称</gcll_name>
			<gcll_type>专线类型</gcll_type>
		</gcll_line>
		<!--ggcll_site记录客户站点信息,如果存在多个客户站点,则传递多个值--> 
		<gcll_site>
			<gcll_name>站点名称</gcll_name>
		</gcll_site>
		<gcll_site>
			<gcll_name>站点名称</gcll_name>
		</gcll_site>
		<!--ggcll_site记录客户信息,如果存在多个客户,则传递多个值--> 
		<gcll_customer>
			<gcll_name>站点名称</gcll_name>
		</gcll_customer>
		<gcll_customer>
			<gcll_name>站点名称</gcll_name>
		</gcll_customer>
	</content>
</responseparam>

可以看到都是xml 格式的。我们这里请求的参数比较少,所以就直接拼接了。

private String queryFromEoms() throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                .append("<requestparam>")
                .append("<content>")
                .append("<id>").append(grid).append("</id >")
                .append("<type>").append(type).append("</type>")
                .append("</content>")
                .append("</requestparam>");
        log.info("------requestxml-------"+sb.toString());
        GridWebServiceSoapBindingStub stub =new GridWebServiceSoapBindingStub();
        return stub.getGridResource(stub.toString());
    }

XML 转json

但是返回给我们也是xml ,这里我们返回给前端xml的话就不好了,所以我们将xml 转成json 来返回。

添加maven 依赖

	<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.67</version>
    </dependency>
	<dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>

xml 转json 工具类


public class XmlUtils {
    public static JSONObject xml2Json(String xmlStr) throws Exception{
        Document doc=  DocumentHelper.parseText(xmlStr);
        JSONObject json=new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml转json
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json){
        //如果是属性
        for(Object o:element.attributes()){
            Attribute attr=(Attribute)o;
            if(!isEmpty(attr.getValue())){
                json.put("@"+attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl=element.elements();
        if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }

        for(Element e:chdEl){//有子元素
            if(!e.elements().isEmpty()){//子元素也有子元素
                JSONObject chdjson=new JSONObject();
                dom4j2Json(e,chdjson);
                Object o=json.get(e.getName());
                if(o!=null){
                    JSONArray jsona=null;
                    if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
                        JSONObject jsono=(JSONObject)o;
                        json.remove(e.getName());
                        jsona=new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if(o instanceof JSONArray){
                        jsona=(JSONArray)o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                }else{
                    if(!chdjson.isEmpty()){
                        json.put(e.getName(), chdjson);
                    }
                }


            }else{//子元素没有子元素
                for(Object o:element.attributes()){
                    Attribute attr=(Attribute)o;
                    if(!isEmpty(attr.getValue())){
                        json.put("@"+attr.getName(), attr.getValue());
                    }
                }
                if(!e.getText().isEmpty()){
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }

}

测试方法

public static void main(String[] args) {
        String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><responseparam><content><id>网格、经营部ID</id><type>1-网格、2-经营部</type><status>0-失败、1-成功</status><notes>失败时反馈失败信息(例:该网格数据不存在、该经营部数据不存在。。。)</notes><gcll_line><gcll_name>专线名称</gcll_name><gcll_type>专线类型</gcll_type></gcll_line><gcll_line><gcll_name>专线名称</gcll_name><gcll_type>专线类型</gcll_type></gcll_line><gcll_site><gcll_name>站点名称</gcll_name></gcll_site><gcll_site><gcll_name>站点名称</gcll_name></gcll_site><gcll_customer><gcll_name>站点名称</gcll_name></gcll_customer><gcll_customer><gcll_name>站点名称</gcll_name></gcll_customer></content></responseparam>";
        try {
            JSONObject jsonObject=XmlUtils.xml2Json(xml);
            System.out.println(jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

返回的格式

{"content":{"gcll_line":[{"gcll_type":"专线类型","gcll_name":"专线名称"},{"gcll_type":"专线类型","gcll_name":"专线名称"}],"notes":"失败时反馈失败信息(例:该网格数据不存在、该经营部数据不存在。。。)","gcll_site":[{"gcll_name":"站点名称"},{"gcll_name":"站点名称"}],"gcll_customer":[{"gcll_name":"站点名称"},{"gcll_name":"站点名称"}],"id":"网格、经营部ID","type":"1-网格、2-经营部","status":"0-失败、1-成功"}}

补充

通过axis 调用

增加maven

	<dependency>
        <groupId>org.apache.axis</groupId>
        <artifactId>axis</artifactId>
        <version>1.4</version>
    </dependency>

代码中直接调用

private String query() throws Exception {
        String endpoint = "http://192.168.1.1:9090/BundleSmart/webservice/GridWebService?wsdl";
        Service service = new Service();
        Call call = (Call)service.createCall();
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName("getGridResource");//WSDL里面描述的接口名称
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                .append("<requestparam>")
                .append("<content>")
                .append("<id>").append(grid).append("</id>")
                .append("<type>").append(type).append("</type>")
                .append("</content>")
                .append("</requestparam>");
        log.info("------requestxml-------"+sb.toString());
        String result = (String)call.invoke(new Object[]{sb.toString()});
        log.info(result);
        return result;
    }

猜你喜欢

转载自blog.csdn.net/qq_27790011/article/details/105272932
今日推荐