/// <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);