private void Button_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.webxml.com.cn/WebServices/WeatherWS.asmx";
string soap = SetSoapMessage();// 构造soap请求信息
string result = GetSOAPReSource(url, soap);
txtShow.Text = result.Replace(">", ">\n").Replace("\n", "");
}
#region 发起SOAP请求
///
/// 发起SOAP请求
///
/// URL
/// 数据
///
public static string GetSOAPReSource(string url, string datastr)
{
//发起请求
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "text/xml; charset=utf-8";
webRequest.Method = "POST";
using (Stream requestStream = webRequest.GetRequestStream())
{
byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
requestStream.Write(paramBytes, 0, paramBytes.Length);
}
//响应
WebResponse webRespOnse= webRequest.GetResponse();
using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string result = "";
return result = myStreamReader.ReadToEnd();
}
}
#endregion
#region 构造soap请求信息
string SetSoapMessage()
{
string header = "";
string body = "";
string fault = "";
body = "";
return GetSoapMessageByBase(header, body, fault);
}
#endregion
#region SOAP消息基本结构
///
/// SOAP消息基本结构
///
/// 头部(包含Header)
/// 内容主体(包含Body)
/// 错误提示(包含Fault)
///
string GetSoapMessageByBase(string header, string body, string fault)
{
StringBuilder soap = new StringBuilder();
soap.Append("");
soap.Append("");
//添加头部
if (!string.IsNullOrWhiteSpace(header))
{
soap.Append("");
soap.Append(header);
soap.Append("");
}
//添加内容
if (!string.IsNullOrWhiteSpace(body))
{
soap.Append("");
soap.Append(body);
//添加错误
if (!string.IsNullOrWhiteSpace(fault))
{
soap.Append("");
soap.Append(fault);
soap.Append("");
}
soap.Append("");
}
soap.Append("");
return soap.ToString();
}
#endregion