1 usingSystem;2 usingSystem.Collections;3 usingSystem.IO;4 usingSystem.Net;5 usingSystem.Text;6 usingSystem.Xml;7 usingSystem.Xml.Serialization;8 namespacePrintFaPiao9 {10 ///
11 ///利用WebRequest/WebResponse进行WebService调用的类12 ///
13 public classWebServiceCaller14 {15 #region Tip:使用说明
16 //webServices 应该支持Get和Post调用,在web.config应该增加以下代码17 //18 //19 //20 //21 //22 //23
24 //调用示例:25 //Hashtable ht = new Hashtable();//Hashtable 为webservice所需要的参数集26 //ht.Add("str", "test");27 //ht.Add("b", "true");28 //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);29 //MessageBox.Show(xx.OuterXml);
30 #endregion
31
32 ///
33 ///需要WebService支持Post调用34 ///
35 public staticXmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)36 {37 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" +MethodName);38 request.Method = "POST";39 request.ContentType = "application/x-www-form-urlencoded";40 SetWebRequest(request);41 byte[] data =EncodePars(Pars);42 WriteRequestData(request, data);43 returnReadXmlResponse(request.GetResponse());44 }45
46 ///
47 ///需要WebService支持Get调用48 ///
49 public staticXmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)50 {51 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" +ParsToString(Pars));52 request.Method = "GET";53 request.ContentType = "application/x-www-form-urlencoded";54 SetWebRequest(request);55 returnReadXmlResponse(request.GetResponse());56 }57
58 ///
59 ///通用WebService调用(Soap),参数Pars为String类型的参数名、参数值60 ///
61 public staticXmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)62 {63 if(_xmlNamespaces.ContainsKey(URL))64 {65 returnQuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());66 }67 else
68 {69 returnQuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));70 }71 }72
73 private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, stringXmlNs)74 {75 _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
76 HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create(URL);77 request.Method = "POST";78 request.ContentType = "text/xml; charset=UTF-8";79 request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");80 SetWebRequest(request);81 byte[] data =EncodeParsToSoap(Pars, XmlNs, MethodName);82 WriteRequestData(request, data);83 XmlDocument doc = new XmlDocument(), doc2 = newXmlDocument();84 doc =ReadXmlResponse(request.GetResponse());85
86 XmlNamespaceManager mgr = newXmlNamespaceManager(doc.NameTable);87 mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");88 String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;89 doc2.LoadXml("" + RetXml + "");90 AddDelaration(doc2);91 returndoc2;92 }93 private static stringGetNamespace(String URL)94 {95 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");96 SetWebRequest(request);97 WebResponse response =request.GetResponse();98 StreamReader sr = newStreamReader(response.GetResponseStream(), Encoding.Default);99 XmlDocument doc = newXmlDocument();100 string test =sr.ReadToEnd();101
102
103 doc.LoadXml(test);104 sr.Close();105 return doc.SelectSingleNode("//@targetNamespace").Value;106 }107
108 private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)109 {110 XmlDocument doc = newXmlDocument();111 doc.LoadXml("");112 AddDelaration(doc);113 //XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
114 XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");115 //XmlElement soapMethod = doc.createElement_x_x(MethodName);
116 XmlElement soapMethod =doc.CreateElement(MethodName);117 soapMethod.SetAttribute("xmlns", XmlNs);118 foreach (string k inPars.Keys)119 {120 //XmlElement soapPar = doc.createElement_x_x(k);
121 XmlElement soapPar =doc.CreateElement(k);122 soapPar.InnerXml =ObjectToSoapXml(Pars[k]);123 soapMethod.AppendChild(soapPar);124 }125 soapBody.AppendChild(soapMethod);126 doc.DocumentElement.AppendChild(soapBody);127 returnEncoding.UTF8.GetBytes(doc.OuterXml);128 }129 private static string ObjectToSoapXml(objecto)130 {131 XmlSerializer mySerializer = newXmlSerializer(o.GetType());132 MemoryStream ms = newMemoryStream();133 mySerializer.Serialize(ms, o);134 XmlDocument doc = newXmlDocument();135 doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));136 if (doc.DocumentElement != null)137 {138 returndoc.DocumentElement.InnerXml;139 }140 else
141 {142 returno.ToString();143 }144 }145
146 ///
147 ///设置凭证与超时时间148 ///
149 ///
150 private static voidSetWebRequest(HttpWebRequest request)151 {152 request.Credentials =CredentialCache.DefaultCredentials;153 request.Timeout = 10000;154 }155
156 private static void WriteRequestData(HttpWebRequest request, byte[] data)157 {158 request.ContentLength =data.Length;159 Stream writer =request.GetRequestStream();160 writer.Write(data, 0, data.Length);161 writer.Close();162 }163
164 private static byte[] EncodePars(Hashtable Pars)165 {166 returnEncoding.UTF8.GetBytes(ParsToString(Pars));167 }168
169 private staticString ParsToString(Hashtable Pars)170 {171 StringBuilder sb = newStringBuilder();172 foreach (string k inPars.Keys)173 {174 if (sb.Length > 0)175 {176 sb.Append("&");177 }178 //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
179 }180 returnsb.ToString();181 }182
183 private staticXmlDocument ReadXmlResponse(WebResponse response)184 {185 StreamReader sr = newStreamReader(response.GetResponseStream(), Encoding.UTF8);186 String retXml =sr.ReadToEnd();187 sr.Close();188 XmlDocument doc = newXmlDocument();189 doc.LoadXml(retXml);190 returndoc;191 }192
193 private static voidAddDelaration(XmlDocument doc)194 {195 XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);196 doc.InsertBefore(decl, doc.DocumentElement);197 }198
199 private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
200 }201 }