标签:
WebServiceCaller
1 /* jonney 2015-09-19 */ 2 3 using System; 4 using System.Collections; 5 using System.Collections.Generic; 6 using System.Globalization; 7 using System.IO; 8 using System.Net; 9 using System.Text; 10 using System.Xml; 11 using System.Xml.Serialization; 12 13 namespace Downloader 14 { 15 /// <summary> 16 /// 利用WebRequest/WebResponse进行WebService调用的类 17 /// </summary> 18 public class WebServiceCaller 19 { 20 /// <summary> 21 /// 需要WebService支持Get调用 22 /// </summary> 23 public static XmlDocument QueryGetWebService(String url, String methodName, Dictionary<string, object> pars) 24 { 25 var request = (HttpWebRequest)WebRequest.Create(url + "/" + methodName + "?" + ParsToString(pars)); 26 request.Method = "GET"; 27 request.ContentType = "application/x-www-form-urlencoded"; 28 SetWebRequest(request); 29 return ReadXmlResponse(request.GetResponse()); 30 } 31 32 /// <summary> 33 /// 需要WebService支持Post调用 34 /// </summary> 35 public static XmlDocument QueryPostWebService(String url, String methodName, Dictionary<string, object> pars) 36 { 37 var request = (HttpWebRequest)WebRequest.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 return ReadXmlResponse(request.GetResponse()); 44 } 45 46 /// <summary> 47 /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值 48 /// </summary> 49 public static XmlDocument QuerySoapWebService(String url, String methodName, Dictionary<string, object> pars) 50 { 51 if (XmlNamespaces.ContainsKey(url + methodName)) 52 { 53 string[] echo = XmlNamespaces[url + methodName].ToString().Split(‘`‘); 54 string xmlNs = echo[0]; 55 string xmlSoapAction = echo[1]; 56 return QuerySoapWebService(url, methodName, pars, xmlNs, xmlSoapAction); 57 } 58 string soapAction = ""; 59 string nameSpace = GetNamespace(url, methodName, ref soapAction); 60 return QuerySoapWebService(url, methodName, pars, nameSpace, soapAction); 61 } 62 63 /// <summary> 64 /// 需要WebService支持Post调用,返回Json 65 /// </summary> 66 public static string QueryPostWebService(String endPoint, StringBuilder postData) 67 { 68 var request = (HttpWebRequest)WebRequest.Create(endPoint); 69 request.Method = "POST"; 70 request.ContentType = "application/json"; 71 SetWebRequest(request); 72 byte[] data = Encoding.UTF8.GetBytes(postData.ToString()); 73 WriteRequestData(request, data); 74 return ReadTxtResponse(request.GetResponse()); 75 } 76 77 /// <summary> 78 /// 需要WebService支持Post调用,返回字节流 79 /// </summary> 80 public static byte[] QueryPostWebService(String endPoint, string postData) 81 { 82 var request = (HttpWebRequest)WebRequest.Create(endPoint); 83 request.Method = "POST"; 84 request.ContentType = "application/json"; 85 SetWebRequest(request); 86 byte[] data = Encoding.UTF8.GetBytes(postData); 87 WriteRequestData(request, data); 88 89 using (var response = (HttpWebResponse)request.GetResponse()) 90 { 91 if (response.StatusCode != HttpStatusCode.OK) 92 { 93 var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode); 94 throw new WebException(message); 95 } 96 using (var result = new MemoryStream()) 97 { 98 const int bufferLen = 2048; 99 var buffer = new byte[bufferLen]; 100 using (var responseStream = response.GetResponseStream()) 101 { 102 var len = responseStream.Read(buffer, 0, bufferLen); 103 while (len > 0) 104 { 105 result.Write(buffer, 0, len); 106 len = responseStream.Read(buffer, 0, bufferLen); 107 } 108 } 109 return result.ToArray(); 110 } 111 } 112 } 113 114 private static XmlDocument QuerySoapWebService(String url, String methodName, Dictionary<string, object> pars, string xmlNs, string soapAction) 115 { 116 XmlNamespaces[url + methodName] = xmlNs + "`" + soapAction;//加入缓存,提高效率 117 var request = (HttpWebRequest)WebRequest.Create(url); 118 request.Method = "POST"; 119 request.ContentType = "text/xml; charset=utf-8;"; 120 string temSoapAction = "\"" + soapAction + "\""; 121 request.Headers.Add("SOAPAction", temSoapAction); 122 SetWebRequest(request); 123 byte[] data = EncodeParsToSoap(pars, xmlNs, methodName); 124 WriteRequestData(request, data); 125 var doc2 = new XmlDocument(); 126 XmlDocument doc = ReadXmlResponse(request.GetResponse()); 127 var mgr = new XmlNamespaceManager(doc.NameTable); 128 mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 129 var xmlNode = doc.SelectSingleNode("//soap:Body/*", mgr); 130 if (xmlNode != null) 131 { 132 String retXml = xmlNode.InnerXml; 133 doc2.LoadXml("<root>" + retXml + "</root>"); 134 } 135 else throw new SystemException("Get soap:Body null"); 136 AddDelaration(doc2); 137 return doc2; 138 } 139 140 private static string GetNamespace(String url, string method, ref string pSoapAction) 141 { 142 var doc = new XmlDocument(); 143 var request = (HttpWebRequest)WebRequest.Create(url + "?wsdl"); 144 SetWebRequest(request); 145 using (var response = (HttpWebResponse)request.GetResponse()) 146 { 147 if (response.StatusCode != HttpStatusCode.OK) 148 { 149 var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode); 150 throw new SystemException(message); 151 } 152 using (var responseStream = response.GetResponseStream()) 153 { 154 if (responseStream != null) 155 { 156 using (var sr = new StreamReader(responseStream, Encoding.UTF8)) 157 { 158 doc.LoadXml(sr.ReadToEnd()); 159 } 160 } 161 else throw new SystemException("GetNamespace url error"); 162 } 163 } 164 var xmlNode = doc.SelectSingleNode("//@targetNamespace"); 165 XmlNodeList soapActionList = doc.SelectNodes("//@soapAction"); 166 if (soapActionList!=null) 167 { 168 for (int i = 0; i < soapActionList.Count; i++) 169 { 170 var item = soapActionList.Item(i); 171 if (item != null && item.Value.EndsWith("/" + method)) 172 { 173 pSoapAction = item.Value; 174 } 175 } 176 } 177 if (xmlNode != null) 178 return xmlNode.Value; 179 throw new SystemException("GetNamespace xmlNode null"); 180 } 181 182 private static byte[] EncodeParsToSoap(Dictionary<string, object> pars, String xmlNs, String methodName) 183 { 184 var doc = new XmlDocument(); 185 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>"); 186 AddDelaration(doc); 187 XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); 188 XmlElement soapMethod = doc.CreateElement(methodName); 189 soapMethod.SetAttribute("xmlns", xmlNs); 190 foreach (string k in pars.Keys) 191 { 192 XmlElement soapPar = doc.CreateElement(k); 193 soapPar.InnerXml = ObjectToSoapXml(pars[k]); 194 soapMethod.AppendChild(soapPar); 195 } 196 soapBody.AppendChild(soapMethod); 197 if (doc.DocumentElement != null) doc.DocumentElement.AppendChild(soapBody); 198 return Encoding.UTF8.GetBytes(doc.OuterXml); 199 } 200 201 private static string ObjectToSoapXml(object o) 202 { 203 var doc = new XmlDocument(); 204 var mySerializer = new XmlSerializer(o.GetType()); 205 using (var ms = new MemoryStream()) 206 { 207 mySerializer.Serialize(ms, o); 208 doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length)); 209 } 210 if (doc.DocumentElement != null) 211 { 212 return doc.DocumentElement.InnerXml; 213 } 214 return o.ToString(); 215 } 216 217 private static void SetWebRequest(HttpWebRequest request) 218 { 219 request.Credentials = CredentialCache.DefaultCredentials; 220 request.Timeout = 10000; 221 } 222 223 private static void WriteRequestData(HttpWebRequest request, byte[] data) 224 { 225 request.ContentLength = data.Length; 226 using (Stream writer = request.GetRequestStream()) 227 { 228 writer.Write(data, 0, data.Length); 229 } 230 } 231 232 private static byte[] EncodePars(Dictionary<string, object> pars) 233 { 234 var sb = new StringBuilder(); 235 sb.Append("{"); 236 foreach (string k in pars.Keys) 237 { 238 if (sb.Length > 1) 239 { 240 sb.Append(","); 241 } 242 sb.Append("\"" + k + "\"" + ":" + "\"" + pars[k] + "\""); 243 } 244 sb.Append("}"); 245 return Encoding.UTF8.GetBytes(sb.ToString()); 246 } 247 248 private static String ParsToString(Dictionary<string, object> pars) 249 { 250 var sb = new StringBuilder(); 251 foreach (string k in pars.Keys) 252 { 253 if (sb.Length > 0) 254 { 255 sb.Append("&"); 256 } 257 sb.Append(k + "=" + pars[k]); 258 } 259 return sb.ToString(); 260 } 261 262 private static XmlDocument ReadXmlResponse(WebResponse resp) 263 { 264 var doc = new XmlDocument(); 265 using (var response = (HttpWebResponse)resp) 266 { 267 if (response.StatusCode != HttpStatusCode.OK) 268 { 269 var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode); 270 throw new SystemException(message); 271 } 272 using (var responseStream = resp.GetResponseStream()) 273 { 274 if (responseStream != null) 275 using (var sr = new StreamReader(responseStream, Encoding.UTF8)) 276 { 277 doc.LoadXml(sr.ReadToEnd()); 278 } 279 } 280 } 281 return doc; 282 } 283 284 private static string ReadTxtResponse(WebResponse resp) 285 { 286 using (var response = (HttpWebResponse)resp) 287 { 288 var responseValue = string.Empty; 289 if (response.StatusCode != HttpStatusCode.OK) 290 { 291 var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode); 292 throw new SystemException(message); 293 } 294 using (var responseStream = response.GetResponseStream()) 295 { 296 if (responseStream != null) 297 using (var sr = new StreamReader(responseStream, Encoding.UTF8)) 298 { 299 responseValue = sr.ReadToEnd(); 300 } 301 } 302 return responseValue; 303 } 304 } 305 306 private static void AddDelaration(XmlDocument doc) 307 { 308 XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); 309 doc.InsertBefore(decl, doc.DocumentElement); 310 } 311 312 private static readonly Hashtable XmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace 313 } 314 }
标签:
原文地址:http://www.cnblogs.com/jonney-wang/p/5724235.html