C#动态调用webservice
最近项目需要调用对方java写的webservice接口
调用示例:
//接收结果
XmlNode xmlNode1; string strSenddata = "";//这个是要发送的报文数据 Hashtable ht = new Hashtable(); ht.Add("xmlIn", strSenddata); xmlNode1 = PrintFaPiao.WebServiceCaller.QuerySoapWebService("http://testservicebus.sinosig.com/servicemgr/services/outputOtherSubject", "outputOtherSubject", ht);//接口地址,方法名,发送报文
WebServiceCaller类:
1 using System; 2 using System.Collections; 3 using System.IO; 4 using System.Net; 5 using System.Text; 6 using System.Xml; 7 using System.Xml.Serialization; 8 namespace PrintFaPiao 9 { 10 /// <summary> 11 /// 利用WebRequest/WebResponse进行WebService调用的类 12 /// </summary> 13 public class WebServiceCaller 14 { 15 #region Tip:使用说明 16 //webServices 应该支持Get和Post调用,在web.config应该增加以下代码 17 //<webServices> 18 // <protocols> 19 // <add name="HttpGet"/> 20 // <add name="HttpPost"/> 21 // </protocols> 22 //</webServices> 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 /// <summary> 33 /// 需要WebService支持Post调用 34 /// </summary> 35 public static XmlDocument 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 return ReadXmlResponse(request.GetResponse()); 44 } 45 46 /// <summary> 47 /// 需要WebService支持Get调用 48 /// </summary> 49 public static XmlDocument 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 return ReadXmlResponse(request.GetResponse()); 56 } 57 58 /// <summary> 59 /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值 60 /// </summary> 61 public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars) 62 { 63 if (_xmlNamespaces.ContainsKey(URL)) 64 { 65 return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString()); 66 } 67 else 68 { 69 return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL)); 70 } 71 } 72 73 private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs) 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 = new XmlDocument(); 84 doc = ReadXmlResponse(request.GetResponse()); 85 86 XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); 87 mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 88 String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml; 89 doc2.LoadXml("<root>" + RetXml + "</root>"); 90 AddDelaration(doc2); 91 return doc2; 92 } 93 private static string GetNamespace(String URL) 94 { 95 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL"); 96 SetWebRequest(request); 97 WebResponse response = request.GetResponse(); 98 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default); 99 XmlDocument doc = new XmlDocument(); 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 = new XmlDocument(); 111 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>"); 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 in Pars.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 return Encoding.UTF8.GetBytes(doc.OuterXml); 128 } 129 private static string ObjectToSoapXml(object o) 130 { 131 XmlSerializer mySerializer = new XmlSerializer(o.GetType()); 132 MemoryStream ms = new MemoryStream(); 133 mySerializer.Serialize(ms, o); 134 XmlDocument doc = new XmlDocument(); 135 doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray())); 136 if (doc.DocumentElement != null) 137 { 138 return doc.DocumentElement.InnerXml; 139 } 140 else 141 { 142 return o.ToString(); 143 } 144 } 145 146 /// <summary> 147 /// 设置凭证与超时时间 148 /// </summary> 149 /// <param name="request"></param> 150 private static void SetWebRequest(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 return Encoding.UTF8.GetBytes(ParsToString(Pars)); 167 } 168 169 private static String ParsToString(Hashtable Pars) 170 { 171 StringBuilder sb = new StringBuilder(); 172 foreach (string k in Pars.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 return sb.ToString(); 181 } 182 183 private static XmlDocument ReadXmlResponse(WebResponse response) 184 { 185 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 186 String retXml = sr.ReadToEnd(); 187 sr.Close(); 188 XmlDocument doc = new XmlDocument(); 189 doc.LoadXml(retXml); 190 return doc; 191 } 192 193 private static void AddDelaration(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 }
如果遇到xml转换错误,可能是编码问题,更改下请求的编码格式或者更改下接收的编码格式(上面例子中开始用utf-8接收结果转换xml的时候提示缺少根元素,于是改成默认编码后编译成功)
代码引用:https://www.cnblogs.com/zpx1986/p/5584370.html