首页 > 开发 > 综合 > 正文

动态调用Webservice

2024-07-21 02:30:22
字体:
来源:转载
供稿:网友
/// <summary>
/// 根据指定的信息,调用远程webservice方法
/// </summary>
/// <param name="url">webservice的http形式的地址</param>
/// <param name="namespace">欲调用的webservice的命名空间</param>
/// <param name="classname">欲调用的webservice的类名(不包括命名空间前缀)</param>
/// <param name="methodname">欲调用的webservice的方法名</param>
/// <param name="args">参数列表</param>
/// <returns>webservice的执行结果</returns>
/// <remarks>
/// 如果调用失败,将会抛出exception。请调用的时候,适当截获异常。
/// 异常信息可能会发生在两个地方:
/// 1、动态构造webservice的时候,compileassembly失败。
/// 2、webservice本身执行失败。
/// </remarks>
/// <example>
/// <code>
/// object obj = invokewebservice("http://localhost/gsp_workflowwebservice/common.asmx","genersoft.platform.service.workflow","common","gettooltype",new object[]{"1"});
/// </code>
/// </example>
private object invokewebservice(string url, string @namespace, string classname, string methodname, object[] args)
{
try
{
system.net.webclient wc = new system.net.webclient();
system.io.stream stream = wc.openread(url+"?wsdl");
system.web.services.description.servicedescription sd = system.web.services.description.servicedescription.read(stream);
system.web.services.description.servicedescriptionimporter sdi = new system.web.services.description.servicedescriptionimporter();
sdi.addservicedescription(sd,"","");
system.codedom.codenamespace cn = new system.codedom.codenamespace(@namespace);
system.codedom.codecompileunit ccu = new system.codedom.codecompileunit();
ccu.namespaces.add(cn);
sdi.import(cn,ccu);

microsoft.csharp.csharpcodeprovider csc = new microsoft.csharp.csharpcodeprovider();
system.codedom.compiler.icodecompiler icc = csc.createcompiler();

system.codedom.compiler.compilerparameters cplist = new system.codedom.compiler.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");

system.codedom.compiler.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));
}
}



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表