/* 第一种方式可以传参、传实体,返回实体 */
ServiceReference1.ServiceSoapClient myclient = new ServiceReference1.ServiceSoapClient();
ServiceReference1.Customer tem = new ServiceReference1.Customer();
tem.cus_id = int.Parse(textBox1.Text);
tem.cus_name = textBox2.Text;
tem.cus_address = textBox3.Text;
string str = JsonHelper.Jso_ToJSON(myclient.getCustomer(tem));
/* 第二种方式可以传参、传实体,返回XmlDom(配置动态灵活,响应处理麻烦了点而已) */
public class WebServiceXmlHelper
{/// <summary>
/// 传递参数来查询
/// </summary>
/// <param name="URL">链接地址</param>
/// <param name="MethodName">函数</param>
/// <param name="Params">参数</param>
/// <returns></returns>
public static XmlDocument QuerySoapWebServiceByParams(String URL, String MethodName, Hashtable Params)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.Accept = @"gzip,deflate";
request.ContentType = @"text/xml; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
byte[] data = EncodeParsToSoap(null,Params, MethodName);
WriteRequestData(request, data);
XmlDocument doc = ReadXmlResponse(request.GetResponse());
return null;
}
/// <summary>
/// 传递实体来查询
/// </summary>
/// <param name="URL">链接地址</param>
/// <param name="MethodName">函数</param>
/// <param name="Params">参数</param>
/// <returns></returns>
public static XmlDocument QuerySoapWebServiceByObject(String URL, String MethodName, String objectName, Hashtable Params)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.Accept = @"gzip,deflate";
request.ContentType = @"text/xml; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
byte[] data = EncodeParsToSoap(objectName,Params, MethodName);
WriteRequestData(request, data);
XmlDocument doc = ReadXmlResponse(request.GetResponse());
return doc;
}
//实体请求
//POST /ServicePort/Service.asmx HTTP/1.1
//Host: localhost
//Content-Type: text/xml; charset=utf-8
//Content-Length: length
//SOAPAction: "http://tempuri.org/getCustomer"
//<?xml version="1.0" encoding="utf-8"?>
//<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:Body>
// <getCustomer xmlns="http://tempuri.org/">
// <cus1>
// <cus_id>int</cus_id>
// <cus_name>string</cus_name>
// <cus_address>string</cus_address>
// </cus1>
// </getCustomer>
// </soap:Body>
//</soap:Envelope>
//参数请求
//POST /ServicePort/Service.asmx HTTP/1.1
//Host: localhost
//Content-Type: text/xml; charset=utf-8
//Content-Length: length
//SOAPAction: "http://tempuri.org/getCustomerFromParams"
//<?xml version="1.0" encoding="utf-8"?>
//<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:Body>
// <getCustomerFromParams xmlns="http://tempuri.org/">
// <id>int</id>
// <name>string</name>
// <address>string</address>
// </getCustomerFromParams>
// </soap:Body>
//</soap:Envelope>
/// <summary>
/// 这里就是凑串,实体凑串、参数凑串 是不一样的。具体参考WebService提供的SOAP 1.1、SOAP 1.2以及HTTP POST(参数请求的话是可以以HTTP POST传递的,实体则不行)
/// </summary>
/// <param name="Params"></param>
/// <param name="MethodName"></param>
/// <param name="ObjectOrNot"></param>
/// <returns></returns>
private static byte[] EncodeParsToSoap(String objectName, Hashtable Params, String MethodName)
{
string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
strXml += "<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/\">";
strXml += "<soap:Body>";
strXml += ("<" + MethodName + " xmlns=\"http://tempuri.org/\">");
if (!(String.IsNullOrEmpty(objectName)))
{
strXml += ("<" + objectName + ">");
foreach (string k in Params.Keys)
{
strXml += ("<" + k + ">" + Params[k] + "</" + k + ">");
}
strXml += ("</" + objectName + ">");
}
else
{
foreach (string k in Params.Keys)
{
strXml += ("<" + k + ">" + Params[k] + "</" + k + ">");
}
}
strXml += ("</" + MethodName + ">");
strXml += "</soap:Body>";
strXml += "</soap:Envelope>";
return Encoding.UTF8.GetBytes(strXml);
}
#region Xml读和写
/// <summary>
/// 写到流中,发送给服务端
/// </summary>
/// <param name="request">HttpWebRequest连接对象</param>
/// <param name="data">要写入连接流发给服务端的内容</param>
private static void WriteRequestData(HttpWebRequest request, byte[] data)
{
request.ContentLength = data.Length;
Stream writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
}
/// <summary>
/// 读取服务端返回的结果
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
private static XmlDocument ReadXmlResponse(WebResponse response)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
String retXml = sr.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(retXml);
return doc;
}
#endregion
}
/* 第三种方式可以传参,返回实体(不能传入一个对象实体,但是配置动态灵活) */
public class WebServiceHelper
{
#region InvokeWebService
/// < summary>
/// 动态调用web服务
/// < /summary>
/// < param name="url">WSDL服务地址< /param>
/// < param name="methodname">方法名< /param>
/// < param name="args">参数< /param>
/// < returns>< /returns>
public static object InvokeWebService(string url, string methodname, object[] args)
{
return WebServiceHelper.InvokeWebService(url, null, methodname, args);
}
/// < summary>
/// 动态调用web服务
/// < /summary>
/// < param name="url">WSDL服务地址< /param>
/// < param name="classname">类名< /param>
/// < param name="methodname">方法名< /param>
/// < param name="args">参数< /param>
/// < returns>< /returns>
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WebServiceHelper.GetWsClassName(url);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider icc = new CSharpCodeProvider();
//设定编译参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//编译代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
/*
PropertyInfo propertyInfo = type.GetProperty(propertyname);
return propertyInfo.GetValue(obj, null);
*/
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
private static string GetWsClassName(string wsUrl)
{
string[] parts = wsUrl.Split('/');
string[] pps = parts[parts.Length - 1].Split('.');
return pps[0];
}
#endregion
}