程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Winform 使用 HttpWebRequest 時設置多值 Cookie 的方法

Winform 使用 HttpWebRequest 時設置多值 Cookie 的方法

編輯:C#入門知識

 

當我們需要發送多值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>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved