有时候难免会在项目中使用到web服务,可以利用vs生成web服务访问代理。不过呢,我们在这儿使用HttpWebReqeust来访问web服务,并访问Cookie
我们以登录操作为例:
1、提交登录数据,并获取Cookie
 System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create("web服务地址");
req.Method = "POST";
//req.ContentType = "application/x-www-form-urlencoded"
req.ContentType = "text/xml; charset=utf-8";
req.Headers.Add("SOAPAction", "\"http://www./Login\"");
req.CookieContainer = new System.Net.CookieContainer();
StringBuilder soap = new StringBuilder();
// 构建SOAP内容 soap.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
soap.AppendLine("<soap:Envelope xmlns:xsi=\"http://www./2001/XMLSchema-instance\" xmlns:xsd=\"http://www./2001/XMLSchema\" xmlns:soap=\"http://schemas./soap/envelope/\">");
soap.AppendLine(" <soap:Body>");
soap.AppendLine(" <Login xmlns=\"http://www./\">");
soap.AppendLine(" <username>用户名</username>");
soap.AppendLine(" <password>密码</password>");
soap.AppendLine(" </Login>");
soap.AppendLine(" </soap:Body>");
soap.AppendLine("</soap:Envelope>");
System.IO.StreamWriter reqStream = new System.IO.StreamWriter(req.GetRequestStream());
reqStream.Write(soap.ToString());
reqStream.Close();
System.Net.HttpWebResponse rep = req.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(rep.GetResponseStream());
//输出返回的数据 TextBox1.Text = reader.ReadToEnd();
reader.Close();
rep.Close();
//获取Cookie System.Net.Cookie cookie = rep.Cookies("cookie名称");
Response.Write(cookie.Value);

2、获取登录用户信息(会话访问),将Cookie发送回服务器端
 System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create("http://www./webtools/webservice/web/youjuhuiservice.asmx");
req.Method = "POST";
req.ContentType = "text/xml; charset=utf-8";
req.Headers.Add("SOAPAction", "\"http://www./GetOnlineUser\"");
req.CookieContainer = new System.Net.CookieContainer();
System.Net.Cookie cookie = new System.Net.Cookie("cookie名称", "cookie值");
cookie.Domain = "www.";
req.CookieContainer.Add(cookie);
StringBuilder soap = new StringBuilder();
// 构建SOAP内容 soap.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
soap.AppendLine("<soap:Envelope xmlns:xsi=\"http://www./2001/XMLSchema-instance\" xmlns:xsd=\"http://www./2001/XMLSchema\" xmlns:soap=\"http://schemas./soap/envelope/\">");
soap.AppendLine(" <soap:Body>");
soap.AppendLine(" <GetOnlineUser xmlns=\"http://www./\" />");
soap.AppendLine(" </soap:Body>");
soap.AppendLine("</soap:Envelope>");
System.IO.StreamWriter reqStream = new System.IO.StreamWriter(req.GetRequestStream());
reqStream.Write(soap.ToString());
reqStream.Close();
System.Net.HttpWebResponse rep = req.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(rep.GetResponseStream());
TextBox1.Text = reader.ReadToEnd();
reader.Close();
rep.Close();

|