【转】

调用Webservice的方法一般是通过右击项目--》添加服务引用--》输入Webservice地址--》前往--》确定,这样可以顺利调用服,但是需要注意的一点是:如果上面的方法是在非启动项项目(比如某个类库)中添加的,在该项目下会自动生成一个app.config文件,而在主配置文件web.config中并没有自动添加上该webservice的标记,这样运行会出现错误,说找不到配置信息等等……所有还需要把app.config中的<system.serviceModel>……</system.serviceModel>这段配置添加到web.config的<configuration>……</configuration>标记中,这样运行就不会出问题了。如果以后服务地址发生了变化,也只需要修改web.config中的地址就行了。

  如果你觉得上面的方法含麻烦的话,你可以选择下面的方法:动态WebService方法。需要写一个底层解析Webservice服务地址的方法,然后调用就可以,很方便。服务地址你可以配置到web.config中,也可以保存到数据库中,随你了……

  下面通过一个判断腾讯QQ在线状态的例子说明一下动态WebService的方法。

腾讯QQ在线状态WEB 服务:http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx

  方法:qqCheckOnline 获得腾讯QQ在线状态

  输入参数:QQ号码 String,默认QQ号码:8698053。返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量

using System;
using System.Collections;
using System.Reflection;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Net;
using System.Web;

namespace Kayang.WebService
{
    /// <summary>
    /// WebServiceProxy 的摘要说明。
    /// </summary>
    public sealed class WebServiceProxy
    {
        private static Hashtable _assenblyCache = null;  //缓存提高效率
        public WebServiceProxy()
        {
        }
        //url:服务地址
     //methodname:方法名字
         //args:方法的参数
        public static object InvokeWebservice(string url, string nsClassName, string methodname, params object[] args)
        {
            , args);
        }
        public static object InvokeWebservice(string url, string nsClassName, string methodname, int timeout, params object[] args)
        {
             && args[] is ArrayList)
            {
                args = (args[] as ArrayList).ToArray();
            }
            try
            {
                int li = nsClassName.LastIndexOf('.');
                 ? , li));

                Assembly assembly;
                if (_assenblyCache == null)
                {
                    _assenblyCache = new Hashtable();
                }
                if (_assenblyCache.ContainsKey(url.ToUpper()))
                {
                    assembly = (Assembly)_assenblyCache[url.ToUpper()];
                }
                else
                {
                    System.Net.WebClient wc = new System.Net.WebClient();
                    System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
                    //Configuration.SoapEnvelopeProcessingElement se = new Configuration.SoapEnvelopeProcessingElement();
                    //se.ReadTimeout = 15000;

                    ServiceDescription sd = ServiceDescription.Read(stream);
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);

                    Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
                    ICodeCompiler icc = csc.CreateCompiler();
                    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 (CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }
                    assembly = cr.CompiledAssembly;
                    _assenblyCache[url.ToUpper()] = assembly;
                }
                Type t = null;
                if (String.IsNullOrEmpty(nsClassName))
                {
                    t = assembly.GetTypes()[];
                }
                else
                {
                    t = assembly.GetType(nsClassName, true, true);
                }
                MethodInfo mi = null;
                if (String.IsNullOrEmpty(methodname))
                {
                    mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)[];
                }
                else
                {
                    mi = t.GetMethod(methodname);
                }
                SoapHttpClientProtocol obj = Activator.CreateInstance(t) as SoapHttpClientProtocol;
                SetCookie(url, obj);
                //obj.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                obj.Timeout = timeout;
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

        /// <summary>
        /// 传入Cookie,使对方可以使用当前Session
        /// By 黄正 2009-12-6
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        private static void SetCookie(string url, SoapHttpClientProtocol obj)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx != null)
            {
                CookieContainer cc = new CookieContainer();
                foreach (string cookieName in ctx.Request.Cookies.AllKeys)
                {
                    cc.SetCookies(new Uri(url), cookieName + "=" + ctx.Request.Cookies[cookieName].Value);
                }
                //req.Headers.Add(HttpRequestHeader.Cookie, Request.Headers["Cookie"]);
                obj.CookieContainer = cc;
            }
        }
    }
}

调用:

string url = "http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx";
string @namespace="";
string methodname = "qqCheckOnline";//需要调用的webservice中的方法
";//QQ号码
string result = WebService.WebServiceProxy.InvokeWebservice(url, @namespace, methodname, Invoke).ToString();

动态WebService方法的更多相关文章

  1. C#动态webservice调用接口 (JAVA,C#)

    C#动态webservice调用接口 using System; using System.Collections; using System.IO; using System.Net; using ...

  2. AX2012 XppCompiler create method动态创建方法并运行

    在用友系列的软件中经常可以看到可配置的计算公式,AX中其实也有可配置的公式,如call center呼叫中心的欺诈Fraud rule的配置,AX后台可以根据配置规则,变量,条件来动态产生方法并执行, ...

  3. winform客户端程序第一次调用webservice方法很慢的解决方法

    .net2.0的winform客户端最常用的与服务端通信方式是通过webservice,最近在用dottrace对客户端做性能测试的时候发现,客户端程序启动以后,第一次调用某一个webservice的 ...

  4. TinyMCE textarea 输入框外部程序动态修改方法

    TinyMCE textarea 输入框外部程序动态修改方法 Public Function C2IE_TINYMCE(ByVal id As String, ByVal value As Strin ...

  5. ios的runtime为什么可以动态添加方法

    一句话概括 每个instance都有一个isa,这个isa,里面含有所有的方法列表,ios提供库函数增加,修改,即实现了动态添加方法

  6. 使用runtime给类动态添加方法并调用 - class_addMethod

    上手开发 iOS 一段时间后,我发现并不能只着眼于完成需求,利用闲暇之余多研究其他的开发技巧,才能在有限时间内提升自己水平.当然,“其他开发技巧”这个命题对于任何一个开发领域都感觉不找边际,而对于我来 ...

  7. Java调用.Net WebService参数为空解决办法 (远程)调试webservice方法 转

    Java调用.Net WebService参数为空解决办法 (远程)调试webservice方法   同事遇到一个很囧的问题,java调,netwebservice的时候,调用无参数方法成功,调用有参 ...

  8. 跨域Ajax请求WebService方法

    一.允许跨域Ajax请求,更改如下配置: 在要调用的WebService上面添加特性标签: 二.以如下返回用户信息的WebService方法为例 三.在另一个网站上通过Ajax访问webService ...

  9. 调用具体webservice方法时时报错误:请求因 HTTP 状态 503 失败: Service Temporarily Unavailable

    添加web引用会在相应项目的app.cofig文件中产生如下代码: <sectionGroup name="applicationSettings" type="S ...

随机推荐

  1. 利用Web服务器网络打洞

    好了有些标题党了.这里想说的是:某些网络,除了http 80服务,其它端口的服务都被限制了,这个时候可以用http web服务器来进行代理转发. 以Apache为例,支持ssh登录到其它服务器的配置如 ...

  2. Spring源码学习之:你不知道的spring注入方式

    前言 在Spring配置文件中使用XML文件进行配置,实际上是让Spring执行了相应的代码,例如: 使用<bean>元素,实际上是让Spring执行无参或有参构造器 使用<prop ...

  3. Latex 编译错误: ! pdfTeX error (ext4): \pdfendlink ended up in different nesting level than \pd fstartlink. 解决方法

    最近写 AAAI 的文章,下载了其模板,但是蛋疼的是,总是提示错误,加上参考文献总是出错: 如下: ! pdfTeX error (ext4): \pdfendlink ended up in dif ...

  4. 论文阅读之 A Convex Optimization Framework for Active Learning

    A Convex Optimization Framework for Active Learning Active learning is the problem of progressively ...

  5. dom4j测试

    book.xml <?xml version="1.0" encoding="UTF-8"?><books><book>&l ...

  6. linux服务之audit

    http://blog.chinaunix.net/uid-20786165-id-3167391.html http://blog.chinaunix.net/uid-8389195-id-1741 ...

  7. linux服务之udevd

    http://www.ibm.com/developerworks/cn/linux/l-cn-udev/[root@localhost ~]# uname -r2.6.32-431.el6.x86_ ...

  8. 推荐一个大文件查找工具---WizTree

    DB备份.dump.电影等文件多了以后,经常遇到磁盘空间不够用的情况,日积月累本来清晰的目录结构找起来也很费劲,尤其是要查找删除无用的大文件.windows本身那差劲的搜索功能就不提了,从搜索引擎上查 ...

  9. 【Reporting Services 报表开发】— 矩阵的使用

    矩阵,相较于数据表示一维的数据,只能指定固定的数据列,来呈现动态的明细数据行,所以,它可以说是种二维的数据展现形式,让我们能够很容易地从数据行和数据集的交替中查看对应的汇总信息.像SQL Server ...

  10. ORA-27086: unable to lock file - already in use

    问题现象: SQL> startup ORACLE instance started. Total System Global Area 1854021632 bytes Fixed Size  ...