C# 不用添加WebService引用,调用WebService方法

来源:互联网 发布:淘宝土特产店铺简介 编辑:程序博客网 时间:2024/06/03 02:27

1、WebService平台技术

  XML+XSD,SOAP和WSDL就是构成WebService平台的三大技术。

  XML+XSD:

  WebService采用HTTP协议传输数据,采用XML格式封装数据(即XML中说明调用远程服务对象的哪个方法,传递的参数是什么,以及服务对象的返回结果是什么)。XML是WebService平台中表示数据的格式。除了易于建立和易于分析外,XML主要的优点在于它既是平台无关的,又是厂商无关的

   WebService通过HTTP协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。SOAP提供了标准的RPC方法来调用Web Service。

  SOAP协议 = HTTP协议 + XML数据格式

  SOAP协议定义了SOAP消息的格式,SOAP协议是基于HTTP协议的,SOAP也是基于XML和XSD的,XML是SOAP的数据编码方式。

 

2、C# 不用添加WebService引用,调用WebService方法

 

 

(1)使用HttpWebRequest 向WebService发送POST请求,并将请求头:ContentType = "application/json;charset=utf-8",参数以JSON方式发送给WebService

复制代码
        /// <summary>        /// 需要WebService支持Post调用        /// </summary>        public static string PostWebServiceByJson(String URL, String MethodName, Hashtable Pars)        {            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);            request.Method = "POST";            request.ContentType = "application/json;charset=utf-8";            request.Credentials = CredentialCache.DefaultCredentials;            request.Timeout = 10000;            byte[] data = Encoding.UTF8.GetBytes(HashtableToJson(Pars));            request.ContentLength = data.Length;            Stream writer = request.GetRequestStream();            writer.Write(data, 0, data.Length);            writer.Close();                        StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8);            String retXml = sr.ReadToEnd();            sr.Close();            return retXml;        }
复制代码

调用方法如下:

复制代码
            Hashtable ht = new Hashtable();            ht.Add("LoginName", "Admin");            ht.Add("Password", "Password");            ht.Add("AppKey", "123");            HttpHelper.PostWebServiceByJson("http://localhost/OpenApi/MobileService.asmx", "Login", ht);
复制代码

注意以上调用WebService方法,需要在WebService中将以下代码中的[System.Web.Script.Services.ScriptService]注释去掉

 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。   [System.Web.Script.Services.ScriptService]

 

 (2)根据WebService文档对应方法说明(例如参数提交方式,请求)发送POST或Get请求

SOAP 1.1

以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /OpenApi/MobileService.asmx HTTP/1.1Host: gps.szwearable.comContent-Type: text/xml; charset=utf-8Content-Length: lengthSOAPAction: "http://tempuri.org/Login"<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  <soap:Body>    <Login xmlns="http://tempuri.org/">      <LoginName>string</LoginName>      <Password>string</Password>      <AppKey>string</AppKey>    </Login>  </soap:Body></soap:Envelope>
HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  <soap:Body>    <LoginResponse xmlns="http://tempuri.org/">      <LoginResult>boolean</LoginResult>    </LoginResponse>  </soap:Body></soap:Envelope>
 以上Soap1.1示例相应代码如下
复制代码
 public static string SoapV1_1WebService(String URL, String MethodName, Hashtable Pars, string 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 + "\"");            // 凭证            request.Credentials = CredentialCache.DefaultCredentials;            //超时时间            request.Timeout = 10000;            byte[] data = HashtableToSoap(Pars, XmlNs, MethodName);            request.ContentLength = data.Length;            Stream writer = request.GetRequestStream();            writer.Write(data, 0, data.Length);            writer.Close();            var response = request.GetResponse();            XmlDocument doc = new XmlDocument();            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);            String retXml = sr.ReadToEnd();            sr.Close();            doc.LoadXml(retXml);            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);            mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");            String xmlStr = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;                       return xmlStr;        }        private static string ObjectToSoapXml(object o)        {            XmlSerializer mySerializer = new XmlSerializer(o.GetType());            MemoryStream ms = new MemoryStream();            mySerializer.Serialize(ms, o);            XmlDocument doc = new XmlDocument();            doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));            if (doc.DocumentElement != null)            {                return doc.DocumentElement.InnerXml;            }            else            {                return o.ToString();            }        }        private static byte[] HashtableToSoap(Hashtable ht, String XmlNs, String MethodName)        {            XmlDocument doc = new XmlDocument();            doc.LoadXml("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"></soap:Envelope>");             XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);            doc.InsertBefore(decl, doc.DocumentElement);            XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");                       XmlElement soapMethod = doc.CreateElement(MethodName);            soapMethod.SetAttribute("xmlns", XmlNs);            foreach (string k in ht.Keys)            {                               XmlElement soapPar = doc.CreateElement(k);                soapPar.InnerXml = ObjectToSoapXml(ht[k]);                soapMethod.AppendChild(soapPar);            }            soapBody.AppendChild(soapMethod);            doc.DocumentElement.AppendChild(soapBody);            return Encoding.UTF8.GetBytes(doc.OuterXml);        }
复制代码

 调用方法如下

复制代码
  Hashtable ht = new Hashtable();            ht.Add("LoginName", "Admin");            ht.Add("Password", "Password");            ht.Add("AppKey", "123");           var data = HttpHelper.SoapV1_1WebService("http://localhost/OpenApi/MobileService.asmx", "Login", ht, "http://tempuri.org/");
复制代码

 

SOAP 1.2

以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /OpenApi/MobileService.asmx HTTP/1.1Host: gps.szwearable.comContent-Type: application/soap+xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  <soap12:Body>    <Login xmlns="http://tempuri.org/">      <LoginName>string</LoginName>      <Password>string</Password>      <AppKey>string</AppKey>    </Login>  </soap12:Body></soap12:Envelope>
HTTP/1.1 200 OKContent-Type: application/soap+xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  <soap12:Body>    <LoginResponse xmlns="http://tempuri.org/">      <LoginResult>boolean</LoginResult>    </LoginResponse>  </soap12:Body></soap12:Envelope>
以上Soap1.2示例相应代码如下
复制代码
        public static string SoapV1_2WebService(String URL, String MethodName, Hashtable Pars, string XmlNs)        {            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);            request.Method = "POST";            request.ContentType = "application/soap+xml; charset=utf-8";            // 凭证            request.Credentials = CredentialCache.DefaultCredentials;            //超时时间            request.Timeout = 10000;            byte[] data = HashtableToSoap12(Pars, XmlNs, MethodName);            request.ContentLength = data.Length;            Stream writer = request.GetRequestStream();            writer.Write(data, 0, data.Length);            writer.Close();            var response = request.GetResponse();            XmlDocument doc = new XmlDocument();            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);            String retXml = sr.ReadToEnd();            sr.Close();            doc.LoadXml(retXml);            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);            mgr.AddNamespace("soap12", "http://www.w3.org/2003/05/soap-envelope");            String xmlStr = doc.SelectSingleNode("//soap12:Body/*/*", mgr).InnerXml;            return xmlStr;        }        private static byte[] HashtableToSoap12(Hashtable ht, String XmlNs, String MethodName)        {            XmlDocument doc = new XmlDocument();            doc.LoadXml("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"></soap12:Envelope>");            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);            doc.InsertBefore(decl, doc.DocumentElement);            XmlElement soapBody = doc.CreateElement("soap12", "Body", "http://www.w3.org/2003/05/soap-envelope");            XmlElement soapMethod = doc.CreateElement(MethodName);            soapMethod.SetAttribute("xmlns", XmlNs);            foreach (string k in ht.Keys)            {                XmlElement soapPar = doc.CreateElement(k);                soapPar.InnerXml = ObjectToSoapXml(ht[k]);                soapMethod.AppendChild(soapPar);            }            soapBody.AppendChild(soapMethod);            doc.DocumentElement.AppendChild(soapBody);            return Encoding.UTF8.GetBytes(doc.OuterXml);        }        private static string ObjectToSoapXml(object o)        {            XmlSerializer mySerializer = new XmlSerializer(o.GetType());            MemoryStream ms = new MemoryStream();            mySerializer.Serialize(ms, o);            XmlDocument doc = new XmlDocument();            doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));            if (doc.DocumentElement != null)            {                return doc.DocumentElement.InnerXml;            }            else            {                return o.ToString();            }        }
复制代码

 调用方法如下

       Hashtable ht = new Hashtable();            ht.Add("LoginName", "Admin");            ht.Add("Password", "Password");            ht.Add("AppKey", "123");       var data = HttpHelper.SoapV1_2WebService("http://localhost/OpenApi/MobileService.asmx", "Login", ht, "http://tempuri.org/");

 

HTTP GET

以下是 HTTP GET 请求和响应示例。所显示的占位符需替换为实际值。

GET /OpenApi/MobileService.asmx/Login?LoginName=string&Password=string&AppKey=string HTTP/1.1Host: gps.szwearable.com
HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><boolean xmlns="http://tempuri.org/">boolean</boolean> 以上GET示例相应代码如下
复制代码
 /// <summary>        /// 需要WebService支持Get调用        /// </summary>        public static string WebServiceGet(String URL, String MethodName, Hashtable Pars)        {            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + HashtableToPostData(Pars));            request.Method = "GET";            request.ContentType = "application/x-www-form-urlencoded";            // 凭证            request.Credentials = CredentialCache.DefaultCredentials;            //超时时间            request.Timeout = 10000;            var response = request.GetResponse();            var stream = response.GetResponseStream();            StreamReader sr = new StreamReader(stream, Encoding.UTF8);            String retXml = sr.ReadToEnd();            sr.Close();            return retXml;        }        private static String HashtableToPostData(Hashtable ht)        {            StringBuilder sb = new StringBuilder();            foreach (string k in ht.Keys)            {                if (sb.Length > 0)                {                    sb.Append("&");                }                sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(ht[k].ToString()));            }            return sb.ToString();        }
复制代码

 调用方法如下

复制代码
Hashtable ht = new Hashtable();            ht.Add("LoginName", "Admin");            ht.Add("Password", "Password");            ht.Add("AppKey", "123");var data = HttpHelper.WebServiceGet("http://localhost/OpenApi/MobileService.asmx", "Login", ht);
复制代码

 

HTTP POST

以下是 HTTP POST 请求和响应示例。所显示的占位符需替换为实际值。

POST /OpenApi/MobileService.asmx/Login HTTP/1.1Host: gps.szwearable.comContent-Type: application/x-www-form-urlencodedContent-Length: lengthLoginName=string&Password=string&AppKey=string
HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><boolean xmlns="http://tempuri.org/">boolean</boolean>

 以上POST示例相应代码如下

复制代码
         /// <summary>        /// 需要WebService支持Post调用        /// </summary>        public static string PostWebService(String URL, String MethodName, Hashtable ht)        {            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);            request.Method = "POST";            request.ContentType = "application/x-www-form-urlencoded";            // 凭证            request.Credentials = CredentialCache.DefaultCredentials;            //超时时间            request.Timeout = 10000;            var PostStr = HashtableToPostData(ht);            byte[] data = System.Text.Encoding.UTF8.GetBytes(PostStr);            request.ContentLength = data.Length;            Stream writer = request.GetRequestStream();            writer.Write(data, 0, data.Length);            writer.Close();            var response = request.GetResponse();            var stream = response.GetResponseStream();            StreamReader sr = new StreamReader(stream, Encoding.UTF8);            String retXml = sr.ReadToEnd();            sr.Close();            return retXml;        }        private static String HashtableToPostData(Hashtable ht)        {            StringBuilder sb = new StringBuilder();            foreach (string k in ht.Keys)            {                if (sb.Length > 0)                {                    sb.Append("&");                }                sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(ht[k].ToString()));            }            return sb.ToString();        }
复制代码

 调用方法如下

  Hashtable ht = new Hashtable();            ht.Add("LoginName", "Admin");            ht.Add("Password", "Password");            ht.Add("AppKey", "123");  var data = HttpHelper.PostWebService("http://localhost/OpenApi/MobileService.asmx", "Login", ht);

WebService支持Post和Get方法

在Web.config,那么只需要修改或添加这么一段

<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 斜挎包肩带长了怎么办 3个月宝宝不吃奶怎么办 米饭扔厕所堵了怎么办 门过梁搭接不够怎么办 华为g7开不了机怎么办 警务通手机丢了怎么办 手机被伪基站覆盖怎么办 听了高频率声音怎么办 qq音乐签到没了怎么办 手机qq音乐不能播放怎么办 台式电脑放歌没有声音怎么办 微信图片上传大愎怎么办 行车记录仪内存卡丢了怎么办 投资项目失败lp的钱怎么办 无线网无ip分配怎么办 为什么电脑的暴风影音打不开怎么办 电枪充电板进水怎么办 捡到一颗子弹该怎么办 防弹衣只保护身体那手臂怎么办? 被子被宝宝尿湿怎么办 眼睛被子弹打了怎么办 gta5买了2套衣服怎么办 gta5车被摧毁了怎么办 gta5车被损坏了怎么办 头盔玻璃磨花了怎么办 浇花喷水壶坏了怎么办 电力专用光缆撞了怎么办 国防电缆挖断了怎么办 国防光缆挖断了怎么办 房门前乱挂光纤线影响住户怎么办 挂断低于限高的光缆怎么办 开大车挂住光缆怎么办 风把树枝挂断压到车该怎么办 货车柴油冻住了怎么办 尖头鞋老是折尖怎么办 打 氟氯西林疼怎么办 多余的十字绣线怎么办 硅胶类的东西沾到蓝药水怎么办? ph计斜率不到90怎么办 ph计斜率低于90怎么办 顾客说衣服起球怎么办