• 调用webservice服务(通过反射的方式动态调用)


     

    调用

                    var xtlb = "68";//系统类别
                    var jkxlh = "";//接口序列号
                    var jkid = "68W05";//接口id
                    string WriteXmlDoc = "";
                    WriteXmlDoc = @"<?xml version=""1.0"" encoding=""UTF-8""?><root><car><GPSBH>B0002</GPSBH><HPZL>02</HPZL><HPHM>鄂AX0007</HPHM><SBSJ>2020-01-07 12:12:34</SBSJ><JD>114.4308450000</JD><WD>30.5208295700</WD><SD>0</SD><FX>0</FX></car></root>";
                    object[] a = new object[4];
                    a[0] = (xtlb);
                    a[1] = ("");
                    a[2] = (jkid);
                    a[3] = (WriteXmlDoc);
                    WebserviceHelper helper = new WebserviceHelper();
                    object result = helper.InvokeWebService("http://localhost:52012/WebService1.asmx", "HelloWorld2", a);
                    string message = result.ToString();

    Webservice 帮助工具类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Net;
    using System.Web.Services.Description;
    using System.CodeDom;
    using Microsoft.CSharp;
    using System.CodeDom.Compiler;
    using System.IO;
    
    namespace ConsoleApp2
    {
        /// <summary>
        /// Webservice 帮助工具类
        /// </summary>
        public  class WebserviceHelper
        {
            public WebserviceHelper() { }
            /// <summary>
            /// 根据 Url 创建 webservice 实例
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="url"></param>
            /// <returns></returns>
            public  T CreateInstance<T>(string url)
            {
                if (url.EndsWith("svc"))
                {
                    return CreateWCF<T>(url);
                }
    
                if (url.EndsWith("asmx"))
                {
                    return CreateAsmx<T>(url);
                }
    
                return default(T);
            }
    
            private  T CreateWCF<T>(string url)
            {
                BasicHttpBinding basicBinding = new BasicHttpBinding();
                CustomBinding binding = new CustomBinding(basicBinding);
                BindingElement binaryElement = new BinaryMessageEncodingBindingElement();
                binding.Elements.Remove(binding.Elements[0]);
                binding.Elements.Insert(0, binaryElement);
    
                EndpointAddress endPoint = new EndpointAddress(url);
    
                T client = (T)Activator.CreateInstance(typeof(T), binding, endPoint);
    
                return client;
            }
    
            private  T CreateAsmx<T>(string url)
            {
                BasicHttpBinding basicBinding = new BasicHttpBinding();
                basicBinding.MaxBufferSize = int.MaxValue;
                basicBinding.MaxReceivedMessageSize = int.MaxValue;
                basicBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
                basicBinding.OpenTimeout = TimeSpan.FromMinutes(1);
    
                CustomBinding binding = new CustomBinding(basicBinding);
                EndpointAddress endPoint = new EndpointAddress(url);
    
                T client = (T)Activator.CreateInstance(typeof(T), binding, endPoint);
    
                return client;
            }
    
            #region 动态调用WebService动态调用地址
            /// < summary>           
            /// 动态调用web服务         
            /// < /summary>          
            /// < param name="url">WSDL服务地址< /param> 
            /// < param name="methodname">方法名< /param>           
            /// < param name="args">参数< /param>           
            /// < returns>< /returns>          
            public  object InvokeWebService(string url, string methodname, object[] args)
            {
                return InvokeWebService(url, null, methodname, args);
            }
            /// <summary>
            /// 动态调用web服务
            /// </summary>
            /// <param name="url">WSDL服务地址</param>
            /// <param name="classname">服务接口类名</param>
            /// <param name="methodname">方法名</param>
            /// <param name="args">参数值</param>
            /// <returns></returns>
            public  object InvokeWebService(string url, string classname, string methodname, object[] args)
            {
    
                string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
                if ((classname == null) || (classname == ""))
                {
                    classname = GetWsClassName(url);
                }
                try
                {
    
                    //获取WSDL   
                    WebClient wc = new WebClient();
                    Stream stream = wc.OpenRead(url + "?WSDL");
                    ServiceDescription sd = ServiceDescription.Read(stream);
                    //注意classname一定要赋值获取 
                    classname = sd.Services[0].Name;
    
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);
    
                    //生成客户端代理类代码          
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    CSharpCodeProvider icc = new CSharpCodeProvider();
    
    
                    //设定编译参数                 
                    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 (true == 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());
                    }
                    //生成代理实例,并调用方法                 
                    System.Reflection.Assembly assembly = cr.CompiledAssembly;
                    Type t = assembly.GetType(@namespace + "." + classname, true, true);
                    object obj = Activator.CreateInstance(t);
                    System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                    return mi.Invoke(obj, args);
    
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                    // return "Error:WebService调用错误!" + ex.Message;
                }
            }
            private  string GetWsClassName(string wsUrl)
            {
                string[] parts = wsUrl.Split('/');
                string[] pps = parts[parts.Length - 1].Split('.');
                return pps[0];
            }
            #endregion
        }
    }
  • 相关阅读:
    struts2(2.0.x到2.1.2版本)的核心和工作原理(转)
    关于Struts2通配符无效的说明
    contOS 网络配置
    INFORMATICA 开发规范
    Python tricks(1) -- 动态定义一个新变量
    MySQL connector c++使用笔记
    python使用set来去重碰到TypeError: unhashable type
    Redis 资料整理
    Ruby 安装和gem配置
    爱读书的犹太人
  • 原文地址:https://www.cnblogs.com/macT/p/12163915.html
Copyright © 2020-2023  润新知