当前位置:编程学习 > C#/ASP.NET >>

Winform 使用 HttpWebRequest 时设置多值 Cookie 的方法

 

当我们需要发送多值Cookie的时候,可以使用下面的方法设置多值  Cookie.

 

C# 代码

System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create("http://www.mengxianhui.com:8081/b.aspx") as System.Net.HttpWebRequest;

r.Headers["Cookie"] = "Url=http://dotnet.aspx.cc; UserInfo=UserName=" + System.Web.HttpUtility.UrlEncode("孟宪会") + "&UserId=net_lover";

r.Proxy = null;

System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse;

this.textBox1.Text = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

response.Close();

或者这样

 

C# 代码

System.Net.CookieCollection ccl = new System.Net.CookieCollection();

System.Net.CookieContainer cc = new CookieContainer();

System.Net.Cookie c = new Cookie("UserInfo","UserName=" + System.Web.HttpUtility.UrlEncode("孟宪会") + "&UserId=net_lover");

c.Domain = "mengxianhui.com";

ccl.Add(c);

c = new Cookie("Url","http://dotnet.aspx.cc");

c.Domain = "mengxianhui.com";

ccl.Add(c);

cc.Add(ccl);

 

System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create("http://www.mengxianhui.com:8081/b.aspx") as System.Net.HttpWebRequest;

r.CookieContainer = cc;

r.Proxy = null;

System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse;

this.textBox1.Text = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

response.Close();

 

 

接收端:

 

ASPX 代码

<%@ Page Language="C#" AutoEventWireup="true" %>

 

<script runat="server">

  protected void Page_Load(object sender, EventArgs e)

  {

    if (Request.Cookies["UserInfo"] != null)

    {

      Response.Write("你设置的分别是Cookie:" + System.Environment.NewLine + System.Environment.NewLine);

      HttpCookie aCookie = Request.Cookies["UserInfo"];

      Response.Write("UserName = " + System.Web.HttpUtility.UrlDecode(aCookie["UserName"]));

      Response.Write(System.Environment.NewLine);

      Response.Write("UserId = " + aCookie["UserId"]);

      Response.Write(System.Environment.NewLine);

      Response.Write("Url = " + Request.Cookies["Url"].Value);

    }

    else

    {

      Response.Write("你没有设置Cookie");

    }

  }

</script>

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,