C#调用java 写的webservice ,但是第一步 webservice 调用本地的WS :
通过本地使用JAVA来调用WS打包成一个代理方法并发布到本地TOMCAT,再通过.net使用request的方法返回结果!基本思路就是这样! 这一步该怎么做
C# 可以直接调用用任何语言编写的 Web Service。
Couldn't create SOAP message due to exception
你java 中接口是怎么写的,可以提供我参考下啊?
com.sun.xml.internal.ws.streaming.XMLStreamReaderException
@比岸灿烂: 你要问的到底是 C# 如何调用 Web Service,还是如何用 Java 编写 Web Service?
@Launcher: 这个不是相通的吗?
@比岸灿烂: 是不是相通的,或者说我不理解你的“相通”的含义,我只能列出点差别:
1、C# 如何调用 Web Service
使用 C# 语言,关注 Web Service 的客户端实现;
2、如何用 Java 编写 Web Service
使用 Java 语言,关注 Web Service 的服务端实现;
首先你要先引用webService,名称可以也自定义,你实例化后,传入需要的参数,调用开放的方法就可以返回你需要的值了
C#动态编译调用WebService
1.配置
<configuration> <configSections> <section name="WebServiceConfiguration" type="Company.Commons.WebServiceConfiguration, Company.Commons"/> </configSections> <WebServiceConfiguration> <UrlCollection> <UrlElement Name="WebService1" Url="http://www.company.com/webservice" ClassName="webservice"/> <UrlElement Name="WebService2" Url="http://www.company.com/webservice2" ClassName="webservice2"/> </UrlCollection> </WebServiceConfiguration> </configuration>
2.代码
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Web.Services.Description; using Newtonsoft.Json; namespace Company.Commons { #region WebService Register /// <summary> /// WebService单例注册类 /// 这样的话,所有的WebService只用动态生成一次 /// 不用每次调用的时候都要动态生成一次 /// </summary> public class WebServiceRegister { private static readonly Lazy<WebServiceRegister> register = new Lazy<WebServiceRegister>(() => new WebServiceRegister()); private WebServiceConfiguration Config { get; set; } private Dictionary<string, Lazy<WebServiceInvoke>> InvokeDic { get; set; } private WebServiceRegister() { Logging.Instance.Trace("WebServiceRegister"); this.Config = WebServiceConfiguration.Config; this.InvokeDic = new Dictionary<string, Lazy<WebServiceInvoke>>(); this.RegisterInvoke(); } /// <summary> /// 注册调用服务 /// </summary> private void RegisterInvoke() { for (int i = 0; i < this.Config.UrlCollection.Count; i++) { UrlElement urlElement = this.Config.UrlCollection[i]; Uri wsUrl = new Uri(urlElement.Url); Lazy<WebServiceInvoke> invoke = new Lazy<WebServiceInvoke>(); if (String.IsNullOrEmpty(urlElement.ClassName)) invoke = new Lazy<WebServiceInvoke>(() => new WebServiceInvoke(wsUrl)); else invoke = new Lazy<WebServiceInvoke>(() => new WebServiceInvoke(wsUrl, urlElement.ClassName)); this.InvokeDic.Add(urlElement.Name, invoke); } } /// <summary> /// 得到WebServiceRegister的单例对像 /// </summary> public static WebServiceRegister Instance { get { return register.Value; } } /// <summary> /// 得到初始化的WebServiceInvoke /// </summary> /// <param name="webServiceName"></param> /// <returns></returns> public WebServiceInvoke GetInvoke(string urlElementName) { if (this.InvokeDic.ContainsKey(urlElementName)) return this.InvokeDic[urlElementName].Value; else throw new Exception("config文件中没有找到对应此配置的数据:" + urlElementName); } } #endregion #region WebService动态调用帮助类 /// <summary> /// WebService动态调用帮助类 /// 调用的时候根据WebService的地址。动态生成调用的代理类 /// </summary> public class WebServiceInvoke { public Assembly Client { get; set; } private string NameSpaceName { get; set; } private string WebServiceUrl { get; set; } private string CalssName { get; set; } /// <summary> /// 初始化WebService调用 /// </summary> /// <param name="appSettingName">配置WebService的Url的appSettings节点名称</param> public WebServiceInvoke(string appSettingName) { this.NameSpaceName = "IFCA.EPC.BL.EPCCommon"; this.GetWebServiceUrl(appSettingName); this.GetWSClassName(); this.InitWebService(); } /// <summary> /// 初始化WebService调用 /// </summary> /// <param name="appSettingName">配置WebService的Url的appSettings节点名称</param> /// <param name="className"> /// 这个WebService初始化的类名 /// wsdl:service节点的name值 /// </param> public WebServiceInvoke(string appSettingName, string className) :this(appSettingName) { this.CalssName = className; } public WebServiceInvoke(Uri wsUrl) { this.NameSpaceName = "IFCA.EPC.BL.EPCCommon"; this.WebServiceUrl = wsUrl.ToString(); this.GetWSClassName(); this.InitWebService(); } public WebServiceInvoke(Uri wsUrl, string className) : this(wsUrl) { this.CalssName = className; } private void GetWebServiceUrl(string appSettingName) { this.WebServiceUrl = System.Configuration.ConfigurationManager.AppSettings[appSettingName]; if (String.IsNullOrEmpty(this.WebServiceUrl)) throw new Exception(String.Format("Web.Config文件中,appSettings节点没有{0}配置内容", appSettingName)); } /// <summary> /// 获取WebService的类名 /// </summary> /// <param name="wsUrl">WebService地址</param> /// <returns>返回WebService的类名</returns> private void GetWSClassName() { string[] parts = this.WebServiceUrl.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); string className = pps[0]; this.CalssName = className; } private void InitWebService() { Logging.Instance.Trace(String.Format("InitWebService:{0}", this.WebServiceUrl)); WebClient wc = new WebClient(); Stream stream = wc.OpenRead(this.WebServiceUrl + "?wsdl"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.ProtocolName = "Soap"; sdi.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理 sdi.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync; sdi.AddServiceDescription(sd, "", "");//添加WSDL文档 CodeNamespace cn = new CodeNamespace(this.NameSpaceName); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider icc = new CSharpCodeProvider(); //ICodeCompiler xxx = icc.CreateCompiler(); CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp"); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 this.Client = cr.CompiledAssembly; //Type[] x = this.Client.GetTypes(); } /// <summary> /// 调用 /// </summary> /// <param name="methodName">方法名</param> /// <param name="args">参数</param> /// <param name="soapHeader">soap的头信息</param> /// <returns></returns> private object Invoke(string methodName, object[] args, SoapHeader soapHeader = null) { Type t = this.Client.GetType(this.NameSpaceName + "." + this.CalssName, true, true); object obj = Activator.CreateInstance(t); #region soapheader信息 PropertyInfo fieldHeader = null; object objHeader = null; if (soapHeader != null) { //fieldHeader = t.GetField(soapHeader.ClassName + "Value"); //当前服务验证头的属性 fieldHeader = t.GetProperty(soapHeader.ClassName + "Value"); Type tHeader = this.Client.GetType(this.NameSpaceName + "." + soapHeader.ClassName); objHeader = Activator.CreateInstance(tHeader); foreach (KeyValuePair<string, object> property in soapHeader.Properties) { PropertyInfo p = tHeader.GetProperty(property.Key); if (p != null) p.SetValue(objHeader, property.Value, null); } } if (soapHeader != null) fieldHeader.SetValue(obj, objHeader, null); #endregion System.Reflection.MethodInfo mi = t.GetMethod(methodName); object resultObj = mi.Invoke(obj, args); return resultObj; } /// <summary> /// 调用WebService /// </summary> /// <typeparam name="T">返回值的类型</typeparam> /// <param name="methodName">要调用WebService接口的方法名称</param> /// <param name="args">接口参数</param> /// <param name="soapHeader">soap头信息</param> /// <returns></returns> public T Invoke<T>(string methodName, object[] args, SoapHeader soapHeader = null) where T : class { T result = this.Invoke(methodName, args, soapHeader) as T; return result; } } #endregion #region WebService Configuration /// <summary> /// 在config中配置WebService的相关数据,用来注册第三方的WebServie /// </summary> public class WebServiceConfiguration : ConfigurationSection { public static WebServiceConfiguration Config { get { return ConfigurationManager.GetSection("WebServiceConfiguration") as WebServiceConfiguration; } } [ConfigurationProperty("UrlCollection", IsRequired = true, IsDefaultCollection = true)] public UrlElementCollection UrlCollection { get { return this["UrlCollection"] as UrlElementCollection; } } } public class UrlElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new UrlElement(); } protected override object GetElementKey(ConfigurationElement element) { UrlElement urlElement = element as UrlElement; return urlElement.Name; } protected override string ElementName { get { return "UrlElement"; } } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } public UrlElement this[int index] { get { return (UrlElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } } /// <summary> /// 每个WebService的配置属性 /// </summary> public class UrlElement : ConfigurationElement { /// <summary> /// 名称(唯一值) /// </summary> [ConfigurationProperty("Name", IsRequired = true, IsKey = true)] public string Name { get { return this["Name"].ToString(); } } /// <summary> /// WebService URL地址 /// </summary> [ConfigurationProperty("Url", IsRequired = true)] public string Url { get { return this["Url"].ToString(); } } /// <summary> /// 初始化的类名称 /// 请参考WebService的WSDL文件(XML)中的(wsdl:service name="这个值")节点 /// </summary> [ConfigurationProperty("ClassName", IsRequired = false)] public string ClassName { get { return this["ClassName"].ToString(); } } public override string ToString() { return String.Format("Name:{0} Url:{1} ClassName:{2}", this.Name, this.Url, this.ClassName); } } #endregion #region Model /// <summary> /// SOAP头 /// </summary> public class SoapHeader { /// <summary> /// 构造一个SOAP头 /// </summary> public SoapHeader() { this.Properties = new Dictionary<string, object>(); } /// <summary> /// 构造一个SOAP头 /// </summary> /// <param name="className">SOAP头的类名</param> public SoapHeader(string className) { this.ClassName = className; this.Properties = new Dictionary<string, object>(); } /// <summary> /// 构造一个SOAP头 /// </summary> /// <param name="className">SOAP头的类名</param> /// <param name="properties">SOAP头的类属性名及属性值</param> public SoapHeader(string className, Dictionary<string, object> properties) { this.ClassName = className; this.Properties = properties; } /// <summary> /// SOAP头的类名 /// </summary> public string ClassName { get; set; } /// <summary> /// SOAP头的类属性名及属性值 /// </summary> public Dictionary<string, object> Properties { get; set; } /// <summary> /// 为SOAP头增加一个属性及值 /// </summary> /// <param name="name">SOAP头的类属性名</param> /// <param name="value">SOAP头的类属性值</param> public void AddProperty(string name, object value) { if (this.Properties == null) { this.Properties = new Dictionary<string, object>(); } this.Properties.Add(name, value); } } #endregion }
3.调用
public void TestWebServiceRegisterInvoke2() { WebServiceRegister register = WebServiceRegister.Instance; WebServiceInvoke helper = register.GetInvoke("WebService1"); var dsm = new { ID = 1, Date = DateTime.Now }; //构建WebService的参数实体 var model = new { UserID = 1, Type = "Demo", JsonData = JsonConvert.SerializeObject(dsm) }; object[] args = new object[] { JsonConvert.SerializeObject(model) }; string resultString = helper.Invoke<string>("ProcessString", args); Assert.IsNotNull(resultString); }
web service本来就是与语言无关了。这个还有问题?我只见过报文不匹配的问题,没见过调不来的问题。你也是让我涨姿势了啊。