资源描述
使用.NET类编写SOAP协议调用Web服务
简介:使用.NET类编写SOAP消息,SOAP消息中包含用户的用户帐号,用户密码和帐号ID。使用HttpWebRequest类发送SOAP请求,请求远程服务器上Web服务程序(客户帐户信息),并使用HttpWebResponse类获取服务响应。
知识点:
命名空间:System.Xml
创建XML文档的类:XmlTextWriter
1. 创建 XmlTextWriter 对象,设置用Tab键缩进
代码示例:
XmlTextWriter BookWriter = new XmlTextWriter( @"\catalog\books.xml", Encoding.UTF8);
BookWriter.Formatting = Formatting.Indented;
2. 编写XML文档的根元素
使用WriteStartDocument()方法和WriteEndDocument()方法创建XML声明
使用WriteStartElement()方法和WriteEndElement()方法创建根元素
代码示例:
BookWriter.WriteStartDocument();
BookWriter.WriteStartElement("books");
// 其他元素
BookWriter.WriteEndElement();
BookWriter.WriteEndDocument();
输出:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<!-- write other elements here -->
</books>
3. 编写元素
使用WriteElementString()方法创建不包含子元素和属性的元素
代码示例:
BookWriter.WriteElementString("price", "19.95");
输出:
<price>19.95</price>
使用WriteStartElement()和WriteEndElement() 方法创建含有下级子元素和属性的元素
代码示例:
BookWriter.WriteStartElement("book");
BookWriter.WriteElementString("price", "19.95");
BookWriter.WriteEndElement();
输出:
<book>
<price>19.95</price>
</book>
4. 编写属性
代码示例:
BookWriter.WriteStartElement("book");
BookWriter.WriteAttributeString("price", "19.95");
BookWriter.WriteEndElement();
输出:
<book price="19.95" />
5. 编写带有命名空间的元素
使用WriteElementString()方法或 WriteStartElement()方法编写带命名空间的元素
代码示例:
BookWriter.WriteStartElement("hr", "Name", "http://hrweb");
BookWriter.WriteString("Nancy Davolio");
BookWriter.WriteEndElement();
输出:
<hr:Name>Nancy Davolio</hr:Name>
6. 编写带有命名空间的属性
使用WriteAttributeString()方法为元素添加带命名空间的属性
public void WriteAttributeString (
string prefix,
string localName,
string ns,
string value
)
参数
prefix:属性的命名空间前缀。
localName:属性的本地名称。
ns:属性的命名空间 URI。
value:属性值。
此方法写出具有用户定义的命名空间前缀的属性,并将其与给定的命名空间进行关联。如果前缀为“xmlns”,则此方法也将此当做命名空间声明对待,并将声明的前缀与给定属性值中提供的命名空间 URI 进行关联。在这种情况下,ns 参数可以为空引用。
代码示例:
xtw.WriteStartElement("bookstore");
// Write the namespace declaration
xtw.WriteAttributeString( "xmlns", "bk", null, "urn:samples");
xtw.WriteStartElement("book");
// Lookup the prefix and then write the ISBN attribute.
string prefix = xtw.LookupPrefix("urn:samples");
xtw.WriteStartAttribute(prefix, "ISBN", "urn:samples");
xtw.WriteString("1-861003-78");
xtw.WriteEndAttribute();
// Write the style element
xtw.WriteStartElement(prefix, "style", "urn:samples");
xtw.WriteString("hardcover");
xtw.WriteEndElement();
// Write the end tag for the book and root elements
xtw.WriteEndElement();
xtw.WriteEndElement();
输出:
<bookstore xmlns:bk="urn:samples">
<book bk:ISBN="1-861003-78">
<bk:style>hardcover</bk:style>
</book>
</bookstore>
任务:演示——使用.NET类构架SOAP协议调用Web服务
第1步:建立BulidSOAPMessage类,添加静态方法SOAPMessage构建SOAP消息。
using System;
using System.IO;
using System.Xml;
using System.Text;
/// <summary>
/// BulidSOAPMessage 的摘要说明
/// </summary>
public class BulidSOAPMessage
{
public static string SOAPMessage(string userID, string password, string acctID)
{
try
{
string str=null;
using( MemoryStream mStream = new MemoryStream()) //创建内存流对象
{
using(XmlTextWriter xtw = new XmlTextWriter(mStream,Encoding.UTF8)) //创建写内存流对象
{
//定义前缀字符串
string xsi = "http://www.w3.org/2001/XMLSchema-instance";
string xsd = "http://www.w3.org/2001/XMLSchema";
string soap = "http://schemas.xmlsoap.org/soap/envelope/";
string namespaceurl = "http://tempuri.org/";
//书写缩进的XML文档,设置用tab键缩进
xtw.Formatting = Formatting.Indented;
//书写版本为“1.0”,并具有独立属性的XML声明,即<?xml version='1.0' encodeding='utf-8'?>
xtw.WriteStartDocument();
//书写开始标记"Envelope",并与给定的命名空间"http://schemas.xmlsoap.org/soap/envelope/"和前缀"soap"关联
xtw.WriteStartElement("soap", "Envelope", soap);
//声明属性 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xtw.WriteAttributeString("xmlns", "xsi", null, xsi);
//声明属性 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xtw.WriteAttributeString("xmlns", "xsd", null, xsd);
//声明属性 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xtw.WriteAttributeString("xmlns", "soap", null, soap);
//声明复合元素“Header”,并与"soap"前缀关联
xtw.WriteStartElement("Header", soap);
//声明“Header”的子元素"WoodgroveAuthInfo",与命名空间nsurl关联,不指定前缀
xtw.WriteStartElement(null, "WoodgroveAuthInfo", namespaceurl);
//声明"WoodgroveAuthInfo"元素内包含的基本元素"Username"和"Password",并赋值
xtw.WriteElementString("Username", userID);
xtw.WriteElementString("Password", password);
//结束"WoodgroveAuthInfo"和“Header”的声明
xtw.WriteEndElement();
xtw.WriteEndElement();
//声明"Body"元素,并与soap命名空间关联
xtw.WriteStartElement("Body", soap);
//声明"Body"元素下的嵌套子元素"GetAccount",关联Web服务给定的命名空间,不设前缀
xtw.WriteStartElement(null, "GetAccount", namespaceurl);
//声明"GetAccount"元素下嵌套的基本元素"acctID",并赋值
xtw.WriteElementString("acctID", acctID);
//结束"GetAccount"和"Body"声明
xtw.WriteEndElement();
xtw.WriteEndElement();
//结束"Envelope"声明
xtw.WriteEndDocument();
//将缓冲区中数据刷新到基础流,并同时刷新基础流
xtw.Flush();
//将基础数据流转换为字符串
str = MemStreamToString(mStream);
}
}
return str;
}
catch
{
return null;
}
}
private static string MemStreamToString(MemoryStream mStream)
{
//将基础流的数据转换为无符号的字节数组
byte[] buffer = mStream.GetBuffer();
//创建把字节序列转换为字符序列的解码器
Decoder d = Encoding.UTF8.GetDecoder();
//创建字符缓冲区,用于存放解码后的字符序列
char[] chars = new char[buffer.Length];
//使用解码器将字节数组转换为字符数组
d.GetChars(buffer, 3, buffer.Length - 3, chars, 0);
//将字符数组转换为字符串
string str = new String(chars);
return str;
}
}
第2步:创建处理类SOAPMessageHandler,使用SOAP协议调用Web服务
using System;
using System.Net;
using System.IO;
/// <summary>
/// SOAPMessageHandler 的摘要说明
/// </summary>
public class SOAPMessageHandler
{
public string SOAPResponse{
get { return _privateSOAPResponse; }
}
private string _privateSOAPResponse = null;
private string _privateSOAPMessage = null;
public SOAPMessageHandler(string userID, string password, string acctID,string uri)
{
//构建SOAP请求消息
_privateSOAPMessage = BulidSOAPMessage.SOAPMessage(userID, password, acctID);
if (_privateSOAPMessage != null)
{
_privateSOAPResponse=this.GetSOAPMessage(uri,_privateSOAPMessage);
}
}
private string GetSOAPMessage(string uri,string content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(uri));
request.ContentType = "text/xml;charset=utf-8";
request.ContentLength = _privateSOAPMessage.Length;
request.Method = "POST";
request.Headers.Add("http://tempuri.org/GetAccount");
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(content);
}
string str=null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
str = reader.ReadToEnd();
}
}
return str;
}
}
7
展开阅读全文