C# 动态调取 soap 接口

调用示例

  string url = "http://localhost:8080/server/PatientService.asmx";    Hashtable ht = new Hashtable();    ht.Add("start_time", starttime); XmlDocument xx = WebServiceCaller.QueryGetWebService(url, soapmethod, ht);

实现方法类

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

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

swap空间的增减方法

(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap

Java获得今日零时零分零秒的时间(Date型)

publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS