.Net下采用GET/POST/SOAP方式動態呼叫WebService的簡易靈活方法(C#)

iDotNetSpace發表於2010-01-06

  一直以來,我都為動態呼叫WebService方法而煩惱。在.Net環境 下,最常用的方法就是採用代理類來呼叫WebService,可以通過改變代理類的Url屬性來實現動態呼叫,但當xmlns改變時就會出錯,似乎要重新 繫結Webservice並重新編譯後才能再次執行。我還試過網上的一種動態編譯並動態呼叫WebService的方式,這種方法效率低,而且需要有較高 的許可權,否則編譯失敗。我曾在Sql Server 2005的CLR儲存過程中用此方法呼叫WebService時,浪費了大半天時間,無論怎麼試它就是不能成功編譯。於是我便不斷思考其他的方法,今天晚 上終於寫了一個類用於動態呼叫WebService,只需傳入WebService地址、需呼叫的方法及其引數,就可以隨時動態呼叫了。現分享給大家,代 碼如下:

using System;
using System.Web;
using System.Xml;
using System.Collections;
using System.Net;
using System.Text;
using System.IO;
/**////


/// 利用WebRequest/WebResponse進行WebService呼叫的類,By 同濟黃正
///

public class WebSvcCaller
...{
    //
    //
    //   
    //   
    //

    //

    private static Hashtable _xmlNamespaces = new Hashtable();//快取xmlNamespace,避免重複呼叫GetNamespace
    /**////
    /// 需要WebService支援Post呼叫
    ///

    public static XmlDocument QueryPostWebService(String URL , String MethodName , Hashtable Pars)
    ...{
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        SetWebRequest(request);
        byte[] data = EncodePars(Pars);
        WriteRequestData(request , data);
        return ReadXmlResponse(request.GetResponse());
    }
    /**////
    /// 需要WebService支援Get呼叫
    ///

    public static XmlDocument QueryGetWebService(String URL , String MethodName , Hashtable Pars)
    ...{
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        SetWebRequest(request);
        return ReadXmlResponse(request.GetResponse());
    }

    /**////


    /// 通用WebService呼叫(Soap),引數Pars為String型別的引數名、引數值
    ///

    public static XmlDocument QuerySoapWebService(String URL , String MethodName , Hashtable Pars)
    ...{
        //By 同濟黃正 http://hz932.ys168.com 2008-3-19
        if (_xmlNamespaces.ContainsKey(URL))
        ...{
            return QuerySoapWebService(URL , MethodName , Pars , _xmlNamespaces[URL].ToString());
        }
        else
        ...{
            return QuerySoapWebService(URL , MethodName , Pars ,GetNamespace(URL));
        }
    }
    private static XmlDocument QuerySoapWebService(String URL , String MethodName , Hashtable Pars , string XmlNs)
    ...{
        _xmlNamespaces[URL] = XmlNs;//加入快取,提高效率
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "text/xml; charset=utf-8";
        request.Headers.Add("SOAPAction" , """ + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + """);
        SetWebRequest(request);
        byte[] data = EncodeParsToSoap(Pars , XmlNs , MethodName);
        WriteRequestData(request , data);
        XmlDocument doc = new XmlDocument() , doc2 = new XmlDocument();
        doc = ReadXmlResponse(request.GetResponse());
        XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
        mgr.AddNamespace("soap" , "http://schemas.xmlsoap.org/soap/envelope/");
        String RetXml = doc.SelectSingleNode("//soap:Body/*" , mgr).InnerXml;
        doc2.LoadXml("" + RetXml + "");
        AddDelaration(doc2);
        return doc2;
    }
    private static string GetNamespace(String URL)
    ...{
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
        SetWebRequest(request);
        WebResponse response = request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream() , Encoding.UTF8);
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sr.ReadToEnd());
        return doc.SelectSingleNode("//@targetNamespace").Value;
    }
    private static byte[] EncodeParsToSoap(Hashtable Pars , String XmlNs , String MethodName)
    ...{
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="0

相關文章