调用示例

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

实现方法类

    /// <summary>
/// 利用WebRequest/WebResponse进行WebService调用的类
/// </summary>
public class WebServiceCaller
{
#region Tip:使用说明
//webServices 应该支持Get和Post调用,在web.config应该增加以下代码
//<webServices>
// <protocols>
// <add name="HttpGet"/>
// <add name="HttpPost"/>
// </protocols>
//</webServices> //调用示例:
//Hashtable ht = new Hashtable(); //Hashtable 为webservice所需要的参数集
//ht.Add("str", "test");
//ht.Add("b", "true");
//XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);
//MessageBox.Show(xx.OuterXml);
#endregion /// <summary>
/// 需要WebService支持Post调用
/// </summary>
public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
SetWebRequest(request);
byte[] data = EncodePars(Pars);
WriteRequestData(request, data);
return ReadXmlResponse(request.GetResponse());
} /// <summary>
/// 需要WebService支持Get调用
/// </summary>
public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
SetWebRequest(request);
return ReadXmlResponse(request.GetResponse());
} /// <summary>
/// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
/// </summary>
public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
{
if (_xmlNamespaces.ContainsKey(URL))
{
return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
}
else
{
return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
}
} private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
{
_xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
SetWebRequest(request);
byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
WriteRequestData(request, data);
XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
doc = ReadXmlResponse(request.GetResponse()); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
doc2.LoadXml("<root>" + RetXml + "</root>");
AddDelaration(doc2);
return doc2;
}
private static string GetNamespace(String URL)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
SetWebRequest(request);
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sr.ReadToEnd());
sr.Close();
return doc.SelectSingleNode("//@targetNamespace").Value;
} private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
{
XmlDocument doc = new XmlDocument();
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>");
AddDelaration(doc);
//XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
//XmlElement soapMethod = doc.createElement_x_x(MethodName);
XmlElement soapMethod = doc.CreateElement(MethodName);
soapMethod.SetAttribute("xmlns", XmlNs);
foreach (string k in Pars.Keys)
{
//XmlElement soapPar = doc.createElement_x_x(k);
XmlElement soapPar = doc.CreateElement(k);
soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
soapMethod.AppendChild(soapPar);
}
soapBody.AppendChild(soapMethod);
doc.DocumentElement.AppendChild(soapBody);
return Encoding.UTF8.GetBytes(doc.OuterXml);
}
private static string ObjectToSoapXml(object o)
{
XmlSerializer mySerializer = new XmlSerializer(o.GetType());
MemoryStream ms = new MemoryStream();
mySerializer.Serialize(ms, o);
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
if (doc.DocumentElement != null)
{
return doc.DocumentElement.InnerXml;
}
else
{
return o.ToString();
}
} /// <summary>
/// 设置凭证与超时时间
/// </summary>
/// <param name="request"></param>
private static void SetWebRequest(HttpWebRequest request)
{
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = ;
} private static void WriteRequestData(HttpWebRequest request, byte[] data)
{
request.ContentLength = data.Length;
Stream writer = request.GetRequestStream();
writer.Write(data, , data.Length);
writer.Close();
} private static byte[] EncodePars(Hashtable Pars)
{
return Encoding.UTF8.GetBytes(ParsToString(Pars));
} private static String ParsToString(Hashtable Pars)
{
StringBuilder sb = new StringBuilder();
foreach (string k in Pars.Keys)
{
if (sb.Length > )
{
sb.Append("&");
}
//sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
}
return sb.ToString();
} private static XmlDocument ReadXmlResponse(WebResponse response)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
String retXml = sr.ReadToEnd();
sr.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(retXml);
return doc;
} private static void AddDelaration(XmlDocument doc)
{
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.InsertBefore(decl, doc.DocumentElement);
} private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
}

C# 动态调取 soap 接口的更多相关文章

  1. C#动态webservice调用接口 (JAVA,C#)

    C#动态webservice调用接口 using System; using System.Collections; using System.IO; using System.Net; using ...

  2. 详解C#泛型(二) 获取C#中方法的执行时间及其代码注入 详解C#泛型(一) 详解C#委托和事件(二) 详解C#特性和反射(四) 记一次.net core调用SOAP接口遇到的问题 C# WebRequest.Create 锚点“#”字符问题 根据内容来产生一个二维码

    详解C#泛型(二)   一.自定义泛型方法(Generic Method),将类型参数用作参数列表或返回值的类型: void MyFunc<T>() //声明具有一个类型参数的泛型方法 { ...

  3. c#动态调用WEBSERVICE接口

    C#动态webservice调用接口 1 using System; 2 using System.Collections; 3 using System.IO; 4 using System.Net ...

  4. C#动态调用WCF接口,两种方式任你选。

    写在前面 接触WCF还是它在最初诞生之处,一个分布式应用的巨作. 从开始接触到现在断断续续,真正使用的项目少之又少,更谈不上深入WCF内部实现机制和原理去研究,最近自己做一个项目时用到了WCF. 从这 ...

  5. PHP调用内容DES加密的SOAP接口

    本文以方倍工作室优惠券接口开发为例,介绍PHP下DES加解密及SOAP接口调用的实现过程. 一.基础概念 DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加 ...

  6. 动态调用wcf接口服务

    1.url:http://localhost:8002/名称.svc/basic(.svc结尾) 2.需要引用的命名空间System.ServiceModel 3.调用代码: public class ...

  7. SSH动态查询封装接口介绍

    SSH动态查询封装接口介绍 1.查询记录总条数 public int count(Class c,Object[][] eq,Object[][] like,String[] group,String ...

  8. C#动态调用WCF接口

    C#动态调用WCF接口 写在前面 接触WCF还是它在最初诞生之处,一个分布式应用的巨作. 从开始接触到现在断断续续,真正使用的项目少之又少,更谈不上深入WCF内部实现机制和原理去研究,最近自己做一个项 ...

  9. 记一次.net core调用SOAP接口遇到的问题

    背景        最近需要将一些外部的Web Service及其他SOAP接口的调用移到一个独立的WebAPI项目中,然后供其他.Net Core项目调用.之前的几个Web Service已经成功迁 ...

随机推荐

  1. PAT 甲级 1144 The Missing Number

    https://pintia.cn/problem-sets/994805342720868352/problems/994805343463260160 Given N integers, you ...

  2. 使用fabric1.14.0和fabric2.4.0

    fabric1.14.0(支持Python2.5-2.7版本): from  fabric.api import * env.gateway = '192.168.181.2'            ...

  3. FZU2121_神庙逃亡

    水题.直接解二次方程判断点的高度即可. #include <iostream> #include <cstring> #include <cstdio> #incl ...

  4. UVA11653_Buses

    这个题目很有意思,一不小心就会让人坑在里面. 题意是这样的,给你n,k,l.分别表示总共的长度,长度为5和10的车的不同颜色数量现在问你要把n的填满有多少种方案. 很多人一开始都会脑子一根筋地想用排列 ...

  5. 最小费用流spfa最小费用路算法模板(pascal)

    3.30: 这篇是以前写的,用的还是指针存图,今天又写了个代码,码风稍微好看点. 传送门:http://www.cnblogs.com/Currier/p/6648685.html --------- ...

  6. Java 读取Excel2007 jar包冲突的问题(org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException)

    1.jar包冲突报错问题 2.使用的jar包,以及重复jar包 3.删除重复jar包

  7. 【BZOJ1491】【NOI2007】社交网络(最短路,动态规划)

    [BZOJ1491][NOI2007]社交网络(最短路,动态规划) 题面 BZOJ 洛谷 图片是假的,只能到OJ上看 Description 在社交网络(socialnetwork)的研究中,我们常常 ...

  8. Redis的String、Hash类型命令

    String是最简单的类型,一个Key对应一个Value,string类型是二进制安全的.Redis的string可以包含任何数据,比如jpg图片或者序列化的对象.最大上限是1G字节.    Hash ...

  9. Linux内核分析3

    周子轩创作品转载请注明出处  <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 gdb跟踪start_ke ...

  10. JAVA导出Excel(支持多sheet)

    一.批量导出: /** * * @Title: expExcel * @Description: 批量导出客户信息 * @param @param params * @param @param req ...