通过HttpWebRequest获取网页内容并保持session,最主要的就是存储cookie。这里使用了一个静态变量m_Cookie用来存储cookie的内容。第二次请求网页的时候把cookie传送过去,这样就可以保持session。

  1. public partial class RequestPage : System.Web.UI.Page
  2. {
  3. private static CookieContainer m_Cookie = new CookieContainer();
  4. private string m_Url = "http://localhost/HttpRequestTest/SessionPage.aspx";
  5. protected void Page_Load(object sender, EventArgs e)
  6. {
  7. string content = GetPageContent();
  8. //string content = GetPageContent(m_Url);
  9. Label1.Text = content;
  10. }
  11. /// <summary>
  12. /// 获取页面内容,保存CookieHeader
  13. /// </summary>
  14. /// <returns></returns>
  15. private string GetPageContent()
  16. {
  17. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_Url);
  18. request.CookieContainer = m_Cookie;
  19. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  20. string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(m_Url));
  21. m_Cookie.SetCookies(new Uri(m_Url), cookieheader);
  22. Stream stream = response.GetResponseStream();
  23. StreamReader reader = new StreamReader(stream);
  24. string result = reader.ReadToEnd();
  25. stream.Close();
  26. reader.Close();
  27. response.Close();
  28. return result;
  29. }
  30. /// <summary>
  31. /// 获取页面内容,存储CookieContainer
  32. /// </summary>
  33. /// <param name="url">被请求页面的url</param>
  34. /// <returns>返回页面内容</returns>
  35. public string GetPageContent(string url)
  36. {
  37. StringBuilder result = new StringBuilder("");
  38. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); ;
  39. HttpWebResponse reponse = null;
  40. try
  41. {
  42. request.CookieContainer = m_Cookie;
  43. reponse = (HttpWebResponse)request.GetResponse();
  44. m_Cookie = request.CookieContainer;
  45. Stream rspStream = reponse.GetResponseStream();
  46. StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.Default);
  47. //获取数据
  48. Char[] read = new Char[256];
  49. int count = sr.Read(read, 0, 256);
  50. while (count > 0)
  51. {
  52. result.Append(read, 0, count);
  53. count = sr.Read(read, 0, 256);
  54. }
  55. }
  56. catch (Exception e)
  57. {
  58. result.Append(e.Message);
  59. }
  60. finally
  61. {
  62. if (reponse != null)
  63. {
  64. reponse.Close();
  65. }
  66. }
  67. return result.ToString();
  68. }
  69. }

【转】HttpWebRequest 保持session的更多相关文章

  1. HttpWebRequest 保存Cookies,模拟Session登录

    前面使用HttpWebRequest 对象可以抓取网页中一些资料,不过有些页面可以直接打开,而有些页面必登录之后才能打开,也就是在登录后保存登录信息在Session,这样就可以访问有权限的页面了.下面 ...

  2. HttpWebRequest调用WebService后台需要Session信息问题的解决办法

    今天在用HttpWebRequest调用后台ASP.NET 的WebService方法时遇到了一个问题,后台的WebService方法里使用到了Session对象中的用户信息,而Session对象中的 ...

  3. web也是区分前端与后端的,session\cookie辨析

    <1>Ajax交互方式 Ext.Ajax.request( { //被用来向服务器发起请求默认的url url : "", //请求时发送后台的参数,既可以是Json对 ...

  4. 通过HttpWebRequest请求与HttpWebResponse响应方式发布接口与访问接口

    一.API接口的编码 1.首页的页面代码: protected void Page_Load(object sender, EventArgs e) { /* * 请求路径:http://xxxx/i ...

  5. C#的提交表单方式主要有两种WebClient与HttpWebRequest

    根据黄聪:C#模拟网站页面POST数据提交表单(转) using System; using System.Collections.Generic; using System.IO; using Sy ...

  6. C#获得和发送网站Session

    request = (HttpWebRequest)WebRequest.Create(url);                                         if (Const. ...

  7. 利用HttpWebRequest和HttpWebResponse获取Cookie

    之前看过某个同学的一篇有关与使用JSoup解析学校图书馆的文章,仔细一看,发现竟然是同校!!既然对方用的是java,那么我也就来个C#好了,虽然我的入门语言是java. C#没有JSoup这样方便的东 ...

  8. C#模拟POST提交表单(二)--HttpWebRequest以及HttpWebResponse

    上次介绍了用WebClient的方式提交POST请求,这次,我继续来介绍用其它一种方式 HttpWebRequest以及HttpWebResponse 自认为与上次介绍的WebClient最大的不同之 ...

  9. WebApi 能支持Session

    由于项目实际需要,我希望让WebApi服务也能支持Session,所以便查找资料按照网上的方法开始着手实验. 然后就有了以下的代码,主要是说让WebApi支持Session,要重写Global.asa ...

随机推荐

  1. duilib入门简明教程 -- 界面布局(9)

        上一个教程实现的标题栏代码中,并没有看到处理自适应窗口大小的代码,但是窗口大小变化后,按钮的位置会跟着变化,这是因为我们将按钮放到了HorizontalLayout.VerticalLayou ...

  2. ES6—— iterator和for-of循环

    Iterator 遍历器的作用:为各种数据结构,提供一个同意的,简便的访问接口.是的数据结构的成员能够按某种次序排列.ES6 新增了遍历命令 for...of 循环,Iterator接口主要供 for ...

  3. 徒手CPR心脏复苏

    CPR 缩写于cardiopulmonary resuscitation. 在危难时刻,能救人救命,意义极其重大,赶紧学起来 成人的CPR 第一步:检查意识 靠近其耳朵,在两耳旁交替大声喊:「你怎么了 ...

  4. Java中获取运行代码的类名、方法名

    以下是案例,已运行通过 package com.hdys; /* * 1.获取当前运行代码的类名,方法名,主要是通过java.lang.StackTraceElement类 * * 2. * [1]获 ...

  5. softmax,softmax loss和cross entropy的讲解

    1 softmax 我们知道卷积神经网络(CNN)在图像领域的应用已经非常广泛了,一般一个CNN网络主要包含卷积层,池化层(pooling),全连接层,损失层等.这一篇主要介绍全连接层和损失层的内容, ...

  6. repo搭建

    [root@op-yum01]# cat /home/work/yumdata/rsync-reposync.sh #!/bin/bash #Purpose: Sync centos7 repos v ...

  7. ubuntu设置root登录ssh

    1. 默认不带ssh,所以需要安装一下ssh sudo apt install openssh-server 2 .设置root密码,ubuntu默认root密码是随机的,需要重置一下 sudo pa ...

  8. leecode刷题(8)-- 两数之和

    leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输 ...

  9. 虚拟机CentOS防火墙设置

    CentOS6关闭防火墙使用以下命令, 开启防火墙 systemctl start firewalld //临时关闭 # service iptables stop //禁止开机启动 # chkcon ...

  10. Ionic2实战——按模块划分app 创建多module

    http://www.jianshu.com/p/d94324b722af 背景 用ionic2开发过一两个小功能的朋友都会发现,每新建一个页面都需要在\src\app\app.module.ts中添 ...