C# 调用WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Web.Services.Description;
using System.Reflection;

namespace Common
{
    public class WebServiceHelper
    {
        /// <summary>
        /// 存放程序集
        /// </summary>
        static Dictionary<string, MethodInfo> methodInfoDictionary = new Dictionary<string, MethodInfo>();
        static Dictionary<string, object> objectDictionary = new Dictionary<string, object>();
        /// <summary>
        /// 动态调用Webservices
        /// </summary>
        /// <param name="methodName">要调用的方法名称</param>
        /// <param name="url">服务地址</param>
        /// <returns></returns>
        public static bool GetServices(string url, string methodName, out object obj, out MethodInfo GetDatall)
        {
            obj = null;
            GetDatall = null;
            try
            {
                if (!methodInfoDictionary.TryGetValue(methodName, out GetDatall) || !objectDictionary.TryGetValue(methodName, out obj))
                {
                    url = url + "?WSDL";
                    //客户端代理服务命名空间,可以设置成需要的值。
                    string ns = string.Format("ProxyServiceReference");
                    //获取WSDL
                    WebClient wc = new WebClient();
                    Log.CreateLog($"服务地址:{url}");
                    Stream stream = wc.OpenRead(url);
                    ServiceDescription sd = ServiceDescription.Read(stream);//服务的描述信息都可以通过ServiceDescription获取
                    string classname = sd.Services[0].Name;
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(ns);

                    //生成客户端代理类代码
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    CSharpCodeProvider csc = 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 = csc.CompileAssemblyFromDom(cplist, ccu);
                    if (cr.Errors.HasErrors == true)
                    {
                        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());
                    }
                    //生成代理实例
                    Assembly assembly = cr.CompiledAssembly;
                    Type t = assembly.GetType(ns + "." + classname, true, true);
                    GetDatall = t.GetMethod(methodName);
                    obj = Activator.CreateInstance(t);

                    methodInfoDictionary.Add(methodName, GetDatall);
                    objectDictionary.Add(methodName, obj);
                }
            }
            catch (Exception ex)
            {
                Log.CreateLog($"动态调用Webservices失败,原因:{ex.ToString()}");
                return false;
            }
            return true;
        }
        /// <summary>
        /// WebService接口返回数据
        /// </summary>
        /// <param name="url">服务地址</param>
        /// <param name="methodName">服务方法名</param>
        /// <param name="XmlParams">参数</param>
        /// <returns></returns>
        public static string GetXmlStr(string url, string methodName, object[] XmlParams)
        {
            try
            {
                string logMsg = string.Format("Invoke Method:url={0},methodName={1}", url, methodName);
                if (XmlParams != null && XmlParams.Length >= 2)
                {
                    logMsg = string.Format(",XmlParams={0}", XmlParams[0] + Environment.NewLine + XmlParams[1]);
                }
                Log.CreateLog(logMsg);
                object obj = null;
                MethodInfo GetDatall = null;
                var result = GetServices(url, methodName, out obj, out GetDatall);
                Log.CreateLog($"服务是否调通:{result.ToString()}");
                Log.CreateLog($"调用服务返回obj:{obj.ToString()}");
                object ResObj = GetDatall.Invoke(obj, XmlParams);
                Log.CreateLog($"调用服务返回结果:{ResObj.ToString()}");
                string xml = ResObj.ToString();
                Log.CreateLog(string.Format("Invoke Method:Result={0}{1}", Environment.NewLine, xml));
                return xml;
            }
            catch (Exception ex)
            {
                Log.CreateLog($"调用服务Error:{ex.ToString()}");
                return "";
            }
        }
        /// <summary>
        /// WebService接口返回数据
        /// </summary>
        /// <param name="url">服务地址</param>
        /// <param name="methodName">服务方法名</param>
        /// <param name="jsonParam">参数为Json</param>
        /// <returns></returns>
        public static string GetJsonStr(string url, string methodName, string jsonParam)
        {
            try
            {
                string logMsg = string.Format("Invoke Method:url={0},methodName={1}", url, methodName);
                Log.CreateLog(logMsg);
                object obj = null;
                MethodInfo GetDatall = null;
                var result = GetServices(url, methodName, out obj, out GetDatall);
                Log.CreateLog($"服务是否调通:{result.ToString()}");
                Log.CreateLog($"调用服务返回obj:{obj.ToString()}");
                object ResObj = GetDatall.Invoke(obj, new object[] { jsonParam});
                Log.CreateLog($"调用服务返回结果:{ResObj.ToString()}");
                string getResult = ResObj.ToString();
                Log.CreateLog(string.Format("Invoke Method:Result={0}{1}", Environment.NewLine, getResult));
                return getResult;
            }
            catch (Exception ex)
            {
                Log.CreateLog($"调用服务Error:{ex.ToString()}");
                return "";
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值