tanhu

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

public class SoapWebService
{
/// <summary>
/// webService 地址
/// </summary>
private string url = "";
public SoapWebService()
{
this.url =ReadPrivateProfile("WEBSERURL", "Url", AppDomain.CurrentDomain.BaseDirectory+@"Bin\MobilePayment.ini");
}

public string QueryPostWebService(string inputData)
{
string methodName = "hosService";
string InText =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+" <soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.freshpower.com.cn\"> "
+ " <soapenv:Header/> "
+ " <soapenv:Body> "
+ " <ser:hosService soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> "
+ " <data xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + inputData + "</data>"
+ " </ser:hosService>"
+ " </soapenv:Body>"
+ " </soapenv:Envelope> ";


string url = this.url;
return GetSOAPReSource(url, InText, methodName);
}

private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ // 总是接受
return true;
}
private string GetSOAPReSource(string url, string datastr, string methodname)
{
try
{
//request
Uri uri = new Uri(url);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.Accept = @"gzip,deflate";
webRequest.ContentType = @"application/soap+xml;charset=UTF-8";
webRequest.UserAgent = @"Apache-HttpClient/4.1.1 (java 1.5)";
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Timeout = 10000;
webRequest.Headers.Add("soapaction", methodname);//axis框架生成的方法,必须添加一个soapaction的头关键字

using (Stream requestStream = webRequest.GetRequestStream())
{
byte[] paramBytes = Encoding.UTF8.GetBytes(datastr);
requestStream.Write(paramBytes, 0, paramBytes.Length);
}
//response
System.Net.WebResponse webResponse = webRequest.GetResponse();
XmlDocument doc = ReadXmlResponse(webResponse);
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
XmlNode node = doc.SelectSingleNode("//soap:Body/*/*", mgr);


return node.InnerText;
}
catch (Exception ex)
{
Log.Error("", ex.Message+"获取WebService异常");
throw ex;
}
}

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;
}
}

posted on 2018-09-14 16:08  tanhu  阅读(804)  评论(0编辑  收藏  举报