Java调用DotNet WebService为什么那么难? .

来源:互联网 发布:2017中国贫富差距数据 编辑:程序博客网 时间:2024/05/10 15:37

前几日研究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 classService : 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开发的最大困难就是资料太多,由于各种包的版本不同,调用的方法也有差异。很难快速找到问题的原因,更多的时候要靠感觉去猜测。即使找到问题,也没时间去仔细研究问题的产生原因。我想这就是我们在享受开源项目所应当承受的无奈,不过这个理由也许有些牵强了。

原创粉丝点击