分享

使用HttpWebRequest访问Web服务,并传递Cookie数据

 昵称10504424 2012-08-28

有时候难免会在项目中使用到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();
复制代码

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多