当前位置:主页 > 软件编程 > JAVA代码 >

Java客户端调用.NET的WebService实例

时间:2021-08-16 09:21:46 | 栏目:JAVA代码 | 点击:

项目需要去调用.NET的WebSrevice,本身是Java,研究了半天,终于有些头绪,记下来。

1,新建.NET WebService。只在原方法上加上一个string类型的参数str

[WebMethod]
public string HelloWorld(string str)
{
  return "Hello World";
}

2,新建Java的WebService客户端,lib引入以下5个jar包(我是用idea生成的WebService客户端,会下载7个包,我试着删掉了log4j和saaj两个包也能正常运行)

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
 
public class HelloWorldClient {
 public static void main(String[] argv) {
   String endpoint ="http://localhost:64662/WebService1.asmx?wsdl";
   try {
     // 定义服务
     Service service = new Service();
     Call call = (Call) service.createCall();
     call.setTargetEndpointAddress(endpoint);
     call.setOperationName(new QName("http://tempuri.org/", "HelloWorld"));
     call.setSOAPActionURI("http://tempuri.org/HelloWorld");
     call.addParameter(new QName("http://tempuri.org/", "str"),// 这里的str对应webservice参数名称
         XMLType.SOAP_STRING, ParameterMode.IN);
     call.setReturnType(XMLType.SOAP_STRING);
     String retVal1 = (String) call.invoke(new Object[] {"Hello World!"});
     System.out.println(retVal1);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
}

注:

1,网上看到有直接写成call.setOperationName("HelloWorld"),我试过不行。不知道是不是跨语言的原因。

2,网上也看到省略call.setSOAPActionURI这 一句的,但我的报错了。

3,其实项目的WebService里面用的参数是实体,我试着Java端通过XMLType.XSD_ANYTYPE类型传实体过去,结果说类型没注册之类的。网上看有方案比较繁琐,倒不如将实体序列化成Json串传过去省事。

4,参数的命名空间参见服务页面

您可能感兴趣的文章:

相关文章