使用AXIS2客戶端調用 WEBSERVICE


問題

在調用WEBSERVICE時,可以使用wsdl2java生成java代碼,調用接口,這種方法在接口固定的情況下是一種不錯的選擇,如果需要動態調用接口,那么這樣就行不通了。

解決辦法

1.直接構建soap包進行調用。

2.使用AXIS2包進行調用,下面代碼就是使用的這種方式。

測試代碼

package wsclient;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class Demo {

    
    private static void axis2WebService() {  
        try {  
            String soapBindingAddress = "http://localhost/x5/service/helloWorld?wsdl";  
            ServiceClient sender = new ServiceClient();  
            EndpointReference endpointReference = new EndpointReference(soapBindingAddress);  
            Options options = new Options();  
        
            options.setTo(endpointReference);  
            sender.setOptions(options);  
            OMFactory fac = OMAbstractFactory.getOMFactory();  
            // 這個和qname差不多,設置命名空間  
            OMNamespace omNs = fac.createOMNamespace("http://impl.webservice.platform.hotent.com/",  "svc");  
            OMElement data = fac.createOMElement("sayHello", omNs);  
            // 對應參數的節點  
            String[] strs = new String[] { "arg0" };  
            // 參數值  
            String[] val = new String[] { "zhangyg" };  
            for (int i = 0; i < strs.length; i++) {  
                QName qname=new QName(strs[i]);
                OMElement inner = fac.createOMElement(qname);  
                inner.setText(val[i]);  
                data.addChild(inner);  
            }  
            // 發送數據,返回結果  
            OMElement result = sender.sendReceive(data);  
            System.out.println(result.toString());  
        } catch (AxisFault ex) {  
            ex.printStackTrace();  
        }  
  
    }  
    public static void main(String[] args) {
        axis2WebService();
    }
}

在測試的時候也遇到了不少問題,使用tcptrace 工具來監控發送和接收的soap包。

image

構建出和soapui一致的請求包。

我精簡了一下jar包,以下是最少需要的jar包。

image

這些包來自AXIS2 1.7.4 包。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM