1.WebService项目结构
SimpleModel类:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DonetWS { public class SimpleModel { public System.Int32 id { set; get; } public System.String str { set; get; } } }
DonetWS.asmx代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace DonetWS { /// <summary> /// DonetWS 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 // [System.Web.Script.Services.ScriptService] public class DonetWS : System.Web.Services.WebService { //测试传参 [WebMethod] public string HelloWorld(string name) { return "Hello World, " + name; } //测试获取对象集合 [WebMethod] public List<SimpleModel> getModelList() { List<SimpleModel> rsltData = new List<SimpleModel>(); SimpleModel model = new SimpleModel(); model.id = 1; model.str = "str1"; rsltData.Add(model); model = new SimpleModel(); model.id = 2; model.str = "str2"; rsltData.Add(model); return rsltData; } } }
run起来:
2.使用Apache Cxf框架实现客户端调用
在Java项目pom.xml 中加入:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.0.3</version> </dependency>
jars:
打开CMD, 在Cxf目录bin文件夹下
运行: wsdl2java -p org.tempuri -d src -client http://localhost:26715/DonetWS.asmx?wsdl
生成以下类:
只留下这4个类, 放到java项目的 org.tempuri 包中
Java项目结构
CxfClient类代码
import java.util.List; import java.util.ResourceBundle; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.dynamic.DynamicClientFactory; import org.tempuri.ArrayOfSimpleModel; import org.tempuri.SimpleModel; public class CxfClient { public static ResourceBundle r = ResourceBundle.getBundle("config"); public static DynamicClientFactory dcf = DynamicClientFactory.newInstance(); public static Client client = dcf.createClient(r.getString("wsdlLocation")); public static void syncHelloWorld() { try { Object[] replys = client.invoke("HelloWorld", "darkdog"); for (Object reply : replys) { String rsltData = (String) reply; System.out.println(rsltData); } } catch (Exception e) { e.printStackTrace(); } } public static void syncGetModelList() { try { Object[] replys = client.invoke("getModelList"); for (Object reply : replys) { ArrayOfSimpleModel arrayOfSimpleModel = (ArrayOfSimpleModel) reply; List<SimpleModel> simpleModels = arrayOfSimpleModel.getSimpleModel(); for(SimpleModel simpleModel : simpleModels) { System.out.println(simpleModel.getId() + " " + simpleModel.getStr()); } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { syncHelloWorld(); syncGetModelList(); } }
config.properties:
wsdlLocation=http\://localhost\:26715/DonetWS.asmx?wsdl
完成!
时间: 2024-11-05 15:57:00