java调用webservice接口方法整理

java调用webservice接口方法整理这几天在调试webservice接口,记录下调试过程以及遇到的问题;1:首先列出几种请求webservice:AXIS调用远程的webserviceSOAP调用远程的webservicewsdl2java把WSDL文件转成本地类,然后像本地类一样使用URLConnection方式当然http方式也有很多,原生httpconnectin,httpclient,okhttp等都可以,springboot也有支持的,封装了上面几个的,具体用哪种方式都可以;2:We_javafor循环中调用webservice接口

大家好,欢迎来到IT知识分享网。java调用webservice接口方法整理"

这几天在调试webservice接口,记录下调试过程以及遇到的问题;

1: 首先列出几种请求webservice:
  1. AXIS调用远程的webservice
    
  2. SOAP调用远程的webservice
    
  3. wsdl2java把WSDL文件转成本地类,然后像本地类一样使用
    
  4. URL Connection方式
    

当然http方式也有很多,原生httpconnectin,httpclient,okhttp等都可以,
springboot也有支持的,封装了上面几个的,具体用哪种方式都可以;

2: WebService不适用场景:

1   考虑性能时不建议使用WebService;
2   重构程序下不建议使用WebService;

我们在测试过程中也用postman来测试webservice接口,下面会贴出来postman的方式;

客户接口说明:

客户给到对应webservice的url地址,后缀为wsdl;

里面有两个url:
  一个链接是wsdl后缀;
  一个url是singleWsdl后缀;
这两个的区别:
  wsdl:(嵌入式WSDL)不能使用它来生成WSDL2java包和不能使用JAX-WS创建连接;
  singleWsdl:(单个WSDL)它可以使用CXF 3.0的WSDL2java生成Java包,并可以使用JAX-WS创建连接;

其中wsdl文件:

<wsdl:operation name="InfInterfaceForJson">
	<soap:operation soapAction="http://XXXXX/InfInterfaceForJson" style="document"/>
	<wsdl:input>
		<soap:body use="literal"/>
	</wsdl:input>
	<wsdl:output>
		<soap:body use="literal"/>
	</wsdl:output>
</wsdl:operation>

这个文件定义了一些方法的说明,上面是我们要调用的方法,
可以看出有输入和输出;
这个文件要关注的点:
1:wsdl:operation:需要调用的方法名
   表示客户的接口,一般都会有多少个接口可以跟客户端交流;
2:soap:operation soapAction:
     如果是.net生成的服务,soapAction是有值的
3:input:表示调用这个方法需要传入的参数
4:output:表示调用这个方法返回的结果。

其中singleWsdl文件:


<xs:element name="InfInterfaceForJson">
	<xs:complexType>
		<xs:sequence>
			<xs:element minOccurs="0" name="function" nillable="true" type="xs:string"/>
			<xs:element minOccurs="0" name="json" nillable="true" type="xs:string"/>
		</xs:sequence>
	</xs:complexType>
</xs:element>
<xs:element name="InfInterfaceForJsonResponse">
	<xs:complexType>
		<xs:sequence>
			<xs:element minOccurs="0" name="InfInterfaceForJsonResult" nillable="true" type="xs:string"/>
		</xs:sequence>
	</xs:complexType>
</xs:element>

说明:
这个文件需要关注的点:
1:targetNamespace=“http://XXXXX”
2:InfInterfaceForJson这个方法是客户提供的通用的json调用方法,
因此我们调用客户的webservice中这个方法,这里面有两个入惨【function】【json】
function:就是我们最终要调用的目标方法名字(客户会给到)
json:目标方法的传参(我们跟客户对接是用的json格式传参的)
3:InfInterfaceForJsonResponse这个是通用的返回;

1:HttpURLConnection 方式

依照上面的客户webservice接口说明:
参数说明:
String urlWsdl:webservice服务地址
String namespace,:
String SOAPAction:
String interfaceName:调用webservice的哪个方法
String function:最终调用的方法名
String json:方法传参

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/** * webservice 请求工具类 */
@Slf4j
public class CallWebServiceUtils { 
   

    private static String soapStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"namespaceData\">" +
            " <soapenv:Header/>" +
            " <soapenv:Body>" +
            " <web:interfaceNameData>" +
            " <web:function>functionData</web:function>" +
            " <web:json>jsonData</web:json>" +
            " </web:interfaceNameData>" +
            " </soapenv:Body>" +
            "</soapenv:Envelope>";


    public static String callWebServiceByHttp(String urlWsdl,String namespace, String SOAPAction,String interfaceName,String function, String json){ 
   
        log.info("callWebServiceByHttp begin json:{}",json);

        /** 关键参数替换 */
        String soapXML = soapStr.replaceAll("namespaceData",namespace)
                .replaceAll("interfaceNameData",interfaceName)
                .replaceAll("functionData",function)
                .replaceAll("jsonData", json);

        HttpURLConnection connection = null;
        try { 
   
            URL url = new URL(urlWsdl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            connection.setRequestProperty("SOAPAction", SOAPAction);
            connection.connect();

            setBytesToOutputStream(connection.getOutputStream(), soapXML.getBytes());

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
   
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);

                log.info("callWebServiceByHttp end json:{} back:{}", json,JSONObject.toJSONString(back));

                String returnData = parseResult(back);

                log.info("callWebServiceByHttp end returnData:{}",returnData);
                return returnData;
            } else { 
   
                log.error("callWebServiceByHttp json:{} httpURLConnection返回状态码:{}",json,connection.getResponseCode());
            }
        } catch (Exception e) { 
   
            e.printStackTrace();
        } finally { 
   
            if (connection != null){ 
   
                connection.disconnect();
            }
        }
        log.error("callWebServiceByHttp error json:{}",json);
        return null;
    }

    /** * 向输入流发送数据 * @param out * @param bytes * @throws IOException */
    private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException { 
   
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] b = new byte[1024];
        int len;
        while ((len = bais.read(b)) != -1) { 
   
            out.write(b, 0, len);
        }
        out.flush();
    }

    /** * 从输入流获取数据 * @param in * @return * @throws IOException */
    private static byte[] getBytesFromInputStream(InputStream in) throws IOException { 
   
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) { 
   
            baos.write(b, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        return bytes;
    }


    /** * 解析结果 * @param s * @return */
    private static String parseResult(String s) { 
   
        String result = "";
        try { 
   
            Reader file = new StringReader(s);
            SAXReader reader = new SAXReader();

            Map<String, String> map = new HashMap<String, String>();
            // 这个替换为targetNamespace
            map.put("ns", "http://XXXXXX");
            reader.getDocumentFactory().setXPathNamespaceURIs(map);
            Document dc = reader.read(file);
            // 这个节点改成你们对应客户接口返回xml格式的数据节点
            result = dc.selectSingleNode("//ns:InfInterfaceForJsonResult").getText().trim();
        } catch (Exception e) { 
   
            e.printStackTrace();
        }
        return result;
    }
}

客户接口返回的是xml:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <InfInterfaceForJsonResponse xmlns="http://XXXX">
            <InfInterfaceForJsonResult>{"code":"Error","errMsg":"数据不存在","data":""}</InfInterfaceForJsonResult>
        </InfInterfaceForJsonResponse>
    </s:Body>
</s:Envelope>

2:postman 请求webservice

用postman做测试也是极好的:
post请求:

url:客户提供的webservice地址

http://XXXX?wsdl

设置请求头:

SOAPAction:http://XXXX/InfInterfaceForJson
这个是调用具体方法的soapaction(.net才会有这个,具体Java作为webservice提供接口有没有,我也不知道哈,各位自己到时候自己看自己的wsdl文件哈)

Content-Type:text/xml;charset=utf-8

请求body:选择raw,XML格式

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="XXXX(targetNamespace)">
<soapenv:Header/>
<soapenv:Body>
    <web:InfInterfaceForJson>
        <web:function>update_user_info</web:function>
        <web:json>{'userId':'123','userName':'李四'}</web:json>
    </web:InfInterfaceForJson>    
</soapenv:Body>
</soapenv:Envelope>

调用客户webservice服务中的InfInterfaceForJson方法,其中有两个入参:
function:最终调用的具体方法
json:最终的目标方法的参数

返回xml:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <InfInterfaceForJsonResponse xmlns="http://XXXXX">
            <InfInterfaceForJsonResult>{"code":"200","msg":"更新成功","data":""}</InfInterfaceForJsonResult>
        </InfInterfaceForJsonResponse>
    </s:Body>
</s:Envelope>

参考文章:
https://www.cnblogs.com/siqi/p/3475222.html
http://www.what21.com/sys/view/java_webservice_1456896211789.html
https://blog.csdn.net/qq_24808729/article/details/80647429

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/27378.html

(0)
上一篇 2023-12-11 17:33
下一篇 2023-12-12 19:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信