Java調用DotNet WebService爲什麼那麼難? .

前幾日研究Java調用DotNet WebService,找了好多資料竟然沒有好用的.將2日的艱辛拿出來分享,希望對朋友們有幫助。

 

.Net開發環境: VS DotNet 2005

Java開發環境:Eclipse3.1+JDK1.6+Axis1.4+mail.jar+activation.jar

第一部分服務器端.Net WebService開發

 

文件-〉新建-〉網站,選擇Asp.net Web服務,建立WebService服務

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

 

[WebService(Namespace = "http://www.my.com/Rpc")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

    public Service () {

 

        //如果使用設計的組件,請取消註釋以下行

        //InitializeComponent();

    }

 

    [WebMethod]

    public string HelloWorld(string name) {

        return "Hello World" + name ;

    }

   

}

注意:

[WebService(Namespace = "http://www.my.com/Rpc")]

http://www.my.com/Rpc根據您的需要自己定義,要寫清楚,Java調用時會使用。

 

第二部分客戶端Java調用.Net WebService

通過Eclipse新建一個Java ProjectProject->Properties下的Java Build Path引入Axis1.4/Lib

Jar文件以及mail.jaractivation.jar(如果你本機沒有這兩個jar就到網上下載一下)。

 

 

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import javax.xml.namespace.QName;

import java.lang.Integer;

 

 

 

publicclass AxisTest {

 

    publicstaticvoid main(String[] args){

    try {

       String varname="haha";

       String endpoint="http://localhost/WebServiceTest/Service.asmx";

       Service service = new Service();

       Call call = (Call)service.createCall();

       call.setTargetEndpointAddress(new java.net.URL(endpoint));

       call.setOperationName(new QName("http://www.my.com/Rpc","HelloWorld"));

       call.addParameter(new QName("http://www.my.com/Rpc","name"),org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);   

       call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);

      

       call.setUseSOAPAction(true);

       call.setSOAPActionURI("http://www.my.com/Rpc/HelloWorld");

      

       String output=(String)call.invoke(new Object[]{varname});

       System.out.println( "result is " + output.toString() + ".");

       }

       catch (Exception e) {System.err.println(e.toString());}

       }

 

}

RunCtrl+F11),大功告成。

 

開發過程中遇到的困難:

1,     call.setSOAPActionURI("http://www.my.com/Rpc/HelloWorld")寫法。

HelloWorldDotNet2005開發的WebService的調用接口。如果不寫清楚,總是返回未知的SoapAction頭錯誤。通過網上的資料你也找不到原因。

2,     call.addParameter(new QName("http://www.my.com/Rpc","name"),org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN)name的寫法。NameDotNet2005開發的WebService接口中的輸入參數名。有好多朋友都問爲什麼接口調用成功了,參數卻不起作用。就是因爲這的寫法有問題。

3,感覺用Java開發的最大困難就是資料太多,由於各種包的版本不同,調用的方法也有差異。很難快速找到問題的原因,更多的時候要靠感覺去猜測。即使找到問題,也沒時間去仔細研究問題的產生原因。我想這就是我們在享受開源項目所應當承受的無奈,不過這個理由也許有些牽強了。

發佈了6 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章