/// <summary>
/// 利用WebRequest/WebResponse进行WebService调用的类
/// </summary>
public class WebServiceHelper
{
//<webServices>
// <protocols>
// <add name="HttpGet"/>
// <add name="HttpPost"/>
// </protocols>
//</webServices>
/// <summary>
/// 需要WebService支持Get调用
/// </summary>
public string QueryGetWebService(string URL, string MethodName, Hashtable Pars)
{
string detilurl = URL + "/" + MethodName + "?" + ParsToString(Pars);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(detilurl);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
SetWebRequest(request);
try
{
return ReadXmlResponseString(request.GetResponse());
}
catch (Exception ex)
{
return "NG:"+ex.ToString();
}
}
/// <summary>
/// 针对信息解读(根据实际调整)
/// </summary>
public string GetReturnInnerMsg(string jsonStr)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(jsonStr);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("ns", "http://wserver");
XmlNode returnNode = doc.SelectSingleNode("//ns:return", xmlnsManager);
if (returnNode != null)
{
if (returnNode.InnerText.Contains(":"))
{
return returnNode.InnerText.Replace(" ","").Split(':')[1];
}
return returnNode.InnerText;
}
else
{
return "";
}
}
/// <summary>
/// 设置WEB请求
/// </summary>
/// <param name="request"></param>
private void SetWebRequest(HttpWebRequest request)
{
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
}
/// <summary>
/// 将Hashtable转换成WEB请求键值对字符串
/// </summary>
/// <param name="Pars"></param>
/// <returns></returns>
private string ParsToString(Hashtable Pars)
{
StringBuilder sb = new StringBuilder();
foreach (string k in Pars.Keys)
{
if (sb.Length > 0)
{
sb.Append("&");
}
// sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
sb.Append(k+ "=" +Pars[k].ToString());
}
return sb.ToString();
}
private string ReadXmlResponseString(WebResponse response)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string retXml = sr.ReadToEnd();
sr.Close();
return retXml;
}
}
接口无非就是拼接字符串发动到指定的网站
POST 与 Get 一样,改下参数就行
例如:
http://localhost:8080/axis2/services/AAAA/getVerifyCode?args0=abc
返回信息
<ns:getVerifyCodeResponse xmlns:ns="http://wserver">
<ns:return>C</ns:return>
</ns:getVerifyCodeResponse>
使用方法
WebServiceHelper webServiceHelper = new WebServiceHelper();
string url="http://localhost:8080/axis2/services/AAAA";
Hashtable ht = new Hashtable(); //创建一个Hashtable实例
//正式库
ht.Add("args0", "abc");
//发送数据
string msg = webServiceHelper.QueryGetWebService(url, "getVerifyCode", ht);
if (msg.Substring(0, 2)=="NG")
{
MessageForm mf = new MessageForm("总成,加密接口通信异常!", msg, true);
mf.ShowDialog();
return;
}
//接收反馈信息
string EnBarCode = webServiceHelper.GetReturnInnerMsg(msg);
-------------------------------------------------------------
asmx 调用: 不推荐,每次使用都需要反射
天气的测试地址
WeatherWebService Web 服务http://www.webxml.com.cn/WebServices/WeatherWebService.asmxwsdl
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
用方法一:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=上海
方法二:
/* 调用方式
* string url = "http://www.webservicex.net/globalweather.asmx" ;
* string[] args = new string[2] ;
* args[0] = "Hangzhou";
* args[1] = "China" ;
* object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;
* Response.Write(result.ToString());
*/
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
}
string url = "http://10.255.30.40:9003/LESPrepareDeliveryService.asmx";
//方法
string fuc = "getSpsMatDt";
//参数
string par = "3210;A1;NS001";
int Pcount = par.Split(';').Count() + 1;
//生成参数信息
string[] args = new string[Pcount];
for (int i = 0; i < Pcount - 1; i++)
{
args[i] = par.Split(';')[i];
}
args[Pcount - 1] = dtm;
//获取Webservice的数据信息
object result = WebServiceHelper.InvokeWebService(url, fuc, args);
DataTable dt = (DataTable)result;
return dt;