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 }
View Code
如果遇到xml转换错误,可能是编码问题,更改下请求的编码格式或者更改下接收的编码格式(上面例子中开始用utf-8接收结果转换xml的时候提示缺少根元素,于是改成默认编码后编译成功)
代码引用:https://www.cnblogs.com/zpx1986/p/5584370.html
转载于:https://www.cnblogs.com/xuxiaoshuan/p/10026526.html
C#动态调用webservice相关推荐
- C# 动态调用WebService
Reference from : http://blog.csdn.net/chuxiamuxiang/article/details/5731988 在C#程序中,若要调用WebService,一般 ...
- C# 动态调用webservice代码
/// <summary> /// 动态调用WebService /// </summary> /// <param name="url">UR ...
- 动态调用WebService方法
C#动态调用WebService object item = InvokeWebService(this._webServicesUrl, "HelloWorld", new ob ...
- 使用AOP动态调用WebService
在网上搜了一下"动态调用WebService"相信都能搜出上千篇文章,但是都出自同一个版本:使用ServiceDescriptionImporter导入wsdl然后进行动态编译,再 ...
- 动态调用Webservice 支持Soapheader身份验证(转)
封装的WebserviceHelp类: using System; using System.CodeDom; using System.CodeDom.Compiler; using System. ...
- vue 调用webservice_用C#通过反射实现动态调用WebService 告别Web引用(转载)
我们都知道,调用WebService可以在工程中对WebService地址进行WEB引用,但是这确实很不方便.我想能够利用配置文件灵活调用WebService.如何实现呢? 用C#通过反射实现动态调用 ...
- vue 调用webservice_动态调用WebService接口的几种方式
一.什么是WebService? 这里就不再赘述了,想要了解的====>传送门 二.为什么要动态调用WebService接口? 一般在C#开发中调用webService服务中的接口都是通过引用过 ...
- 动态调用WebService
public class WebServiceHelper{//动态调用web服务public static object InvokeWebService(string url, string me ...
- Silverlight 动态调用 WebService
1. 配置 IIS 绑定 IP地址 2. 在 SL 中引用 WebService 3. 在需要调用 WebService 的地方写下列代码: WCF : WCF BasicHttpBinding b ...
- .NET动态调用WebService
这不是一篇教你了解WebService的博文,也不是对WebService的深入理解, 这是一篇教你在开发过程中,如果动态的调用WebService一个方法. 在比较常见的WebService调用,我 ...
最新文章
- 2.3.5 用信号量实现 进程互斥 同步 前驱关系
- Qt 4.8.4 Qt Creator 2.6.1 安装和配置(Windows)
- 《深入剖析NGINX》学习记录
- GDB下查看内存命令(x命令)
- ARGB和PARGB
- Android Studio 设置代码提示和代码自动补全快捷键
- .NET Core通讯模块在Linux下的性能测试
- 标准模板库(STL)之 priority_queue 列传
- 电脑网络问题——IPv4无Internet访问权限
- 使用Python-OpenCV将图片批量转换为jpg格式
- 差分放大电路的基本工作原理是什么//2021-2-18
- 线性规划python
- JS document方法
- 卷积网络中的通道(Channel)和特征图
- 深度学习图像分类:植物幼苗图像分类入门(Plant Seedlings Classification)
- java 中 webcam类,使用WebCam实现java拍照功能
- 【全文翻译】ML-Leaks: Model and Data Independent Membership Inference Attacks and Defenses on Machine.....
- 【测试】了解软件测试
- 谷粒商城的前端商品发布功能选择分类后没有发送请求获取关联品牌的相关问题解决
- 每日学习——4.4号
热门文章
- hive的变量传递设置
- Lua date format
- __slots__(面向对象进阶)
- PAT 1041. 考试座位号(15)
- 在移动端禁用长按选中文本功能
- 在Linux环境下使用OpenSSL对消息和文件进行加密(转载)
- 微软(北京).NET俱乐部 2008雪上激情之旅-续
- undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status
- Android开发四年以来的工作难点总结
- 电脑卡,eclipse Android stadio 卡,什么都卡解决方法