c#soap调用WebService

辅助类

 /// <summary>
    /// 上传数据参数
    /// </summary>
    public class UploadEventArgs : EventArgs
    {
        int bytesSent;
        int totalBytes;
        /// <summary>
        /// 已发送的字节数
        /// </summary>
        public int BytesSent
        {
            get { return bytesSent; }
            set { bytesSent = value; }
        }
        /// <summary>
        /// 总字节数
        /// </summary>
        public int TotalBytes
        {
            get { return totalBytes; }
            set { totalBytes = value; }
        }
    }

    /// <summary>
    /// 下载数据参数
    /// </summary>
    public class DownloadEventArgs : EventArgs
    {
        int bytesReceived;
        int totalBytes;
        byte[] receivedData;
        /// <summary>
        /// 已接收的字节数
        /// </summary>
        public int BytesReceived
        {
            get { return bytesReceived; }
            set { bytesReceived = value; }
        }
        /// <summary>
        /// 总字节数
        /// </summary>
        public int TotalBytes
        {
            get { return totalBytes; }
            set { totalBytes = value; }
        }
        /// <summary>
        /// 当前缓冲区接收的数据
        /// </summary>
        public byte[] ReceivedData
        {
            get { return receivedData; }
            set { receivedData = value; }
        }
    }

    public class WebClient2
    {
        Encoding encoding = Encoding.UTF8;
        string respHtml = "";
        WebProxy proxy;
        static CookieContainer cc;
        WebHeaderCollection requestHeaders;
        WebHeaderCollection responseHeaders;
        int bufferSize = 15240;
        public event EventHandler<UploadEventArgs> UploadProgressChanged;
        public event EventHandler<DownloadEventArgs> DownloadProgressChanged;
        static WebClient2()
        {
            LoadCookiesFromDisk();
        }
        /// <summary>
        /// 创建WebClient的实例
        /// </summary>
        public WebClient2()
        {
            requestHeaders = new WebHeaderCollection();
            responseHeaders = new WebHeaderCollection();
        }
        /// <summary>
        /// 设置发送和接收的数据缓冲大小
        /// </summary>
        public int BufferSize
        {
            get { return bufferSize; }
            set { bufferSize = value; }
        }
        /// <summary>
        /// 获取响应头集合
        /// </summary>
        public WebHeaderCollection ResponseHeaders
        {
            get { return responseHeaders; }
        }
        /// <summary>
        /// 获取请求头集合
        /// </summary>
        public WebHeaderCollection RequestHeaders
        {
            get { return requestHeaders; }
        }
        /// <summary>
        /// 获取或设置代理
        /// </summary>
        public WebProxy Proxy
        {
            get { return proxy; }
            set { proxy = value; }
        }
        /// <summary>
        /// 获取或设置请求与响应的文本编码方式
        /// </summary>
        public Encoding Encoding
        {
            get { return encoding; }
            set { encoding = value; }
        }
        /// <summary>
        /// 获取或设置响应的html代码
        /// </summary>
        public string RespHtml
        {
            get { return respHtml; }
            set { respHtml = value; }
        }
        /// <summary>
        /// 获取或设置与请求关联的Cookie容器
        /// </summary>
        public CookieContainer CookieContainer
        {
            get { return cc; }
            set { cc = value; }
        }
        /// <summary>
        ///  获取网页源代码
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns></returns>
        public string GetHtml(string url)
        {
            HttpWebRequest request = CreateRequest(url, "GET");
            respHtml = encoding.GetString(GetData(request));
            return respHtml;
        }

        public CredentialCache CredentialCache
        {
            get;
            set;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件URL地址</param>
        /// <param name="filename">文件保存完整路径</param>
        public void DownloadFile(string url, string filename)
        {
            FileStream fs = null;
            try
            {
                HttpWebRequest request = CreateRequest(url, "GET");
                byte[] data = GetData(request);
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                fs.Write(data, 0, data.Length);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
        /// <summary>
        /// 从指定URL下载数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns></returns>
        public byte[] GetData(string url)
        {
            HttpWebRequest request = CreateRequest(url, "GET");
            return GetData(request);
        }
        /// <summary>
        /// 向指定URL发送文本数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="postData">urlencode编码的文本数据</param>
        /// <returns></returns>
        public string Post(string url, string postData)
        {
            byte[] data = encoding.GetBytes(postData);
            return Post(url, data);
        }
        /// <summary>
        /// 向指定URL发送字节数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="postData">发送的字节数组</param>
        /// <returns></returns>
        public string Post(string url, byte[] postData, string contentType = "application/x-www-form-urlencoded")
        {
            HttpWebRequest request = CreateRequest(url, "POST");
            request.ContentType = contentType;
            request.ContentLength = postData.Length;
            request.KeepAlive = true;
            PostData(request, postData);
            respHtml = encoding.GetString(GetData(request));
            return respHtml;
        }
        /// <summary>
        /// 向指定URL发送字节数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="postData">发送的字节数组</param>
        /// <returns></returns>
        public string Post(string url, string data, WebHeaderCollection header, string contentType = "application/x-www-form-urlencoded")
        {
            byte[] postData = encoding.GetBytes(data);
            HttpWebRequest request = CreateRequest(url, "POST");
            request.ContentType = contentType;
            request.ContentLength = postData.Length;
            request.KeepAlive = true;
            foreach (string key in header.Keys)
            {
                request.Headers.Add(key, header[key]);
            }
            PostData(request, postData);
            respHtml = encoding.GetString(GetData(request));
            return respHtml;
        }
        /// <summary>
        /// 向指定网址发送mulitpart编码的数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="mulitpartForm">mulitpart form data</param>
        /// <returns></returns>
        //public string Post(string url, MultipartForm mulitpartForm)
        //{
        //    HttpWebRequest request = CreateRequest(url, "POST");
        //    request.ContentType = mulitpartForm.ContentType;
        //    request.ContentLength = mulitpartForm.FormData.Length;
        //    request.KeepAlive = true;
        //    PostData(request, mulitpartForm.FormData);
        //    var stream = GetData(request);
        //    respHtml = encoding.GetString(stream);
        //    return respHtml;
        //}
        /// <summary>
        /// 读取请求返回的数据
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <returns></returns>
        private byte[] GetData(HttpWebRequest request)
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            responseHeaders = response.Headers;
            //SaveCookiesToDisk();

            DownloadEventArgs args = new DownloadEventArgs();
            if (responseHeaders[HttpResponseHeader.ContentLength] != null)
                args.TotalBytes = Convert.ToInt32(responseHeaders[HttpResponseHeader.ContentLength]);

            MemoryStream ms = new MemoryStream();
            int count = 0;
            byte[] buf = new byte[bufferSize];
            while ((count = stream.Read(buf, 0, buf.Length)) > 0)
            {
                ms.Write(buf, 0, count);
                if (this.DownloadProgressChanged != null)
                {
                    args.BytesReceived += count;
                    args.ReceivedData = new byte[count];
                    Array.Copy(buf, args.ReceivedData, count);
                    this.DownloadProgressChanged(this, args);
                }
            }
            stream.Close();
            //解压
            if (ResponseHeaders[HttpResponseHeader.ContentEncoding] != null)
            {
                MemoryStream msTemp = new MemoryStream();
                count = 0;
                buf = new byte[100];
                switch (ResponseHeaders[HttpResponseHeader.ContentEncoding].ToLower())
                {
                    case "gzip":
                        GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
                        while ((count = gzip.Read(buf, 0, buf.Length)) > 0)
                        {
                            msTemp.Write(buf, 0, count);
                        }
                        return msTemp.ToArray();
                    case "deflate":
                        DeflateStream deflate = new DeflateStream(ms, CompressionMode.Decompress);
                        while ((count = deflate.Read(buf, 0, buf.Length)) > 0)
                        {
                            msTemp.Write(buf, 0, count);
                        }
                        return msTemp.ToArray();
                    default:
                        break;
                }
            }
            return ms.ToArray();
        }
        /// <summary>
        /// 发送请求数据
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <param name="postData">请求发送的字节数组</param>
        private void PostData(HttpWebRequest request, byte[] postData)
        {
            int offset = 0;
            int sendBufferSize = bufferSize;
            int remainBytes = 0;
            Stream stream = request.GetRequestStream();
            UploadEventArgs args = new UploadEventArgs();
            args.TotalBytes = postData.Length;
            while ((remainBytes = postData.Length - offset) > 0)
            {
                if (sendBufferSize > remainBytes) sendBufferSize = remainBytes;
                stream.Write(postData, offset, sendBufferSize);
                offset += sendBufferSize;
                if (this.UploadProgressChanged != null)
                {
                    args.BytesSent = offset;
                    this.UploadProgressChanged(this, args);
                }
            }
            stream.Close();
        }
        /// <summary>
        /// 创建HTTP请求
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <returns></returns>
        private HttpWebRequest CreateRequest(string url, string method)
        {
            Uri uri = new Uri(url);

            if (uri.Scheme == "https")
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);

            // Set a default policy level for the "http:" and "https" schemes.
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);
            HttpWebRequest.DefaultCachePolicy = policy;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.AllowAutoRedirect = false;
            request.AllowWriteStreamBuffering = false;
            request.Method = method;
            if (CredentialCache != null)
            {
                request.Credentials = CredentialCache;
                //string authByte ="NTLM " + Convert.ToBase64String(new ASCIIEncoding().GetBytes
                //    (
                //        CredentialCache.DefaultNetworkCredentials.UserName + ":" +
                //        CredentialCache.DefaultNetworkCredentials.Password
                //    ));
                //request.Headers.Add("Authorization", authByte);
            }
            if (proxy != null) request.Proxy = proxy;
            request.CookieContainer = cc;
            foreach (string key in requestHeaders.Keys)
            {
                request.Headers.Add(key, requestHeaders[key]);
            }
            requestHeaders.Clear();
            return request;
        }
        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        /// <summary>
        /// 将Cookie保存到磁盘
        /// </summary>
        private static void SaveCookiesToDisk()
        {
            string cookieFile = System.Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\webclient.cookie";
            FileStream fs = null;
            try
            {
                fs = new FileStream(cookieFile, FileMode.Create);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formater.Serialize(fs, cc);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
        /// <summary>
        /// 从磁盘加载Cookie
        /// </summary>
        private static void LoadCookiesFromDisk()
        {
            cc = new CookieContainer();
            string cookieFile = System.Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\webclient.cookie";
            if (!File.Exists(cookieFile))
                return;
            FileStream fs = null;
            try
            {
                fs = new FileStream(cookieFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                cc = (CookieContainer)formater.Deserialize(fs);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
    }

用法

         WebHeaderCollection header = new WebHeaderCollection();
                header.Add("SOAPAction", string.Format("‘{0}‘", SOAPAction));
                var postData = string.Format(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=‘http://schemas.xmlsoap.org/soap/envelope/‘ xmlns:SOAP-ENC=‘http://schemas.xmlsoap.org/soap/encoding/‘ xmlns:xsi=‘http://www.w3.org/2001/XMLSchema-instance‘ xmlns:xsd=‘http://www.w3.org/2001/XMLSchema‘>
    <SOAP-ENV:Body>
        <m:NewContactExOrder xmlns:m=‘http://siebel.com/asi/BYM‘>
            <InXml xsi:type=‘xsd:string‘><![CDATA[{0}]]></InXml>
            <Source xsi:type=‘xsd:string‘>{1}</Source>
        </m:NewContactExOrder>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>", inXml, source);

                WebClient2 wc = new WebClient2();
                var response = wc.Post(url, postData, header, "text/xml; Charset=UTF-8");
时间: 2024-10-06 14:13:26

c#soap调用WebService的相关文章

sqlserver2008 中使用MSXML2.ServerXMLHttp拼装soap调用webservice

要调用的接口方法:UP_ACC_inst_Info(string xml) 接口参数:xml格式的字符串 接口功能:传递人员编号.备注到接口进行更新,接口返回更新结果. 实例: declare @strXML varchar(5000)declare @obj intdeclare @sUrl varchar(5000)declare @response varchar(5000)declare @hr int--参数SET @strXML ='<root><accountid>6

C# 通过Get、Post、Soap调用WebService的方法

实现代码来源于网络,我只是作了一些修改! using System; using System.Web; using System.Xml; using System.Collections; using System.Net; using System.Text; using System.IO; using System.Xml.Serialization; /// <summary> /// 利用WebRequest/WebResponse进行WebService调用的类 /// <

C#实现SOAP调用WebService

position:static(静态定位) 当position属性定义为static时,可以将元素定义为静态位置,所谓静态位置就是各个元素在HTML文档流中应有的位置 podisition定位问题.所以当没有定义position属性时,并不说明该元素没有自己的位置,它会遵循默认显示为静态位置,在静态定位状态下无法通过坐标值(top,left,right,bottom)来改变它的位置. position:absolute(绝对定位) 当position属性定义为absolute时,元素会脱离文档流

C#实现SOAP调用WebService转佐足尊灼尊

position:static(静态定位) 当position属性定义为static时,可以将元素定义为静态位置,所谓静态位置就是各个元素在HTML文档流中应有的位置 podisition定位问题.所以当没有定义position属性时,并不说明该元素没有自己的位置,它会遵循默认显示为静态位置,在静态定位状态下无法通过坐标值(top,left,right,bottom)来改变它的位置. position:absolute(绝对定位) 当position属性定义为absolute时,元素会脱离文档流

[转]Net 下采用GET/POST/SOAP方式动态调用WebService C#实现

本文转自:http://www.cnblogs.com/splendidme/archive/2011/10/05/2199501.html 一直以来,我们都为动态调用WebService方法而烦恼.在.Net环境下,最常用的方法就是采用代理类来调用WebService,可以通过改变代理类的Url属性来实现动态调用,但当xmlns改变时就会出错,似乎要重新绑定Webservice并重新编译后才能再次运行.我无意中通过百度搜索找了一个采用GET/POST/SOAP方式动态调用WebService的

PHP使用SOAP调用.net的WebService数据

需要和一个.net系统进行数据交换,对方提供了一个WebService接口,使用PHP如何调用这个数据呢,下面就看看使用SOAP调用的方法吧 这个与一般的PHP POST或GET传值再查库拿数据的思路有点不一样,需要用到SOAP模块,处理方法也很简单,就是有一些需要注意的事情.首先确认你的PHP.ini开启了.SOAP,就是 extension=php_soap.dll 这前面的分号去咯.代码很简单: 复制代码代码如下: <?php $client = new SoapClient('http:

python发布及调用基于SOAP的webservice

现如今面向服务(SOA)的架构设计已经成为主流,把公用的服务打包成一个个webservice供各方调用是一种非常常用的做法,而应用最广泛的则是基于SOAP协议和wsdl的webservice.本文讲解python环境下如何发布及调用一个基于SOAP的webservice,基于soaplib(发布)和suds(调用). OS:ubuntu 14.04  python:2.7.6 服务端: 1.安装: 服务端要使用的工具包是soaplib,遗憾的是现在也停止维护了,不过好在还能用,下载地址在http

php 如何利用 soap调用.Net的WebService asmx文件

原文:php 如何利用 soap调用.Net的WebService asmx文件 最近,帮一个同行测试用.net写的WebService接口,C#调用通过,现在需要测试一下php版本对它的调用,经过各种探索, 相关的PHP调用webservice的过程如下: 1.打开php相关扩展: 找到配置文件php.ini 文件, 打开以下扩展 extension = php_soap.dllextension = php_curl.dllextension = php_openssl.dll 2.php代

php soap调用asp.net webservice

原文:php soap调用asp.net webservice 首先做一下准备工作,找到安装环境里的php.ini把;extension=php_soap.dll去掉前面的;.我这里使用的是wamp,php-php扩展里把php_soap启用就可以了. 一.用vs2008新建一个webservice:using System;using System.Linq;using System.Web;using System.Web.Services;using System.Web.Services