问题:有的网站的相关内容必须要在登录后才可以查看,其登录信息保存在session变量之中。这样,使用asphttp等组件就难以正确得到所要的信息。
  
  解决:使用asp.net中的httprequest和httpresponse来实现。
  
  要点:
  1。 通过附加一个cookiecontainer到httprequest对象中,可以得到登录后返回的代表SESSION ID的COOKIE。 见Login方法
  2。 将此COOKIE包含在一个cookiecontainer中并附加到另一个HTTPREQUEST请求中,则可以实现SESSION的还原。见getPage方法
  
  源程序如下:
  
  getHttpInfo.aspx:
  <%@ Page language="c#" Codebehind="getHttpInfo.aspx.cs" AutoEventWireup="false" Inherits="PdfTest.getHttpInfo" %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
  <HTML>
  <HEAD>
  <title>WebForm1</title>
  <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  </HEAD>
  <body>
  <form id="Form1" method="post" runat="server">
  </form>
  </body>
  </HTML>
  
  
  getHttpInfo.aspx.cs:
  using System;
  using System.Collections;
  using System.ComponentModel;
  using System.Data;
  //using System.Data.OleDb;
  using System.Drawing;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;
  using System.Net;
  using System.IO;
  using System.Text;
  using System.Text.RegularExpressions;
  using Microsoft.Data.Odbc;
  
  namespace PdfTest
  {
  /// <summary>
  /// Summary description for WebForm1.
  /// </summary>
  public class getHttpInfo : System.Web.UI.Page
  {
  protected static string cookieheader;
  
  
  private void Page_Load(object sender, System.EventArgs e)
  {
  // Put user code to initialize the page here
  
  string strResult;
  
  if (HttpContext.Current.Application["cookieheader"] != null)
  {
  cookieheader = (string)HttpContext.Current.Application["cookieheader"];
  }
  else
  {
  //Login into the website and keep the cookie for the session in the application variable
  string strLogin = Login("http://www.thesiteyouwanttovisit/theloginpage.asp", "Action=&USERID=&Password=") ;
  }
  
  
  strResult = getPage("http://www.thesiteyouwanttovisit/theloginpage.asp", "Action=&data=") ;
  
  
  //Write the result to htm file
  FileStream htmFile = new FileStream("c:\save.htm", FileMode.OpenOrCreate);
  StreamWriter sw = new StreamWriter(htmFile);
  sw.Write(strResult);
  sw.Close();
  htmFile.Close();
  
  // output the result
  Response.Write(strResult);
  }
  
  
  public static string Login(String url, String paramList)
  {
  HttpWebResponse res = null;
  string strResult="";
  
  try
  {
  
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  req.Method = "POST";
  req.ContentType = "application/x-www-form-urlencoded";
  req.AllowAutoRedirect = false;
  CookieContainer cookieCon = new CookieContainer();
  req.CookieContainer = cookieCon;
  
  StringBuilder UrlEncoded = new StringBuilder();
  Char[] reserved = {'?', '=', '&'};
  byte[] SomeBytes = null;
  
  if (paramList != null)
  {
  int i=0, j;
  while(i<paramList.Length)
  {
  j=paramList.IndexOfAny(reserved, i);
  if (j==-1)
  {
  UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
  break;
  }
  UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
  UrlEncoded.Append(paramList.Substring(j,1));
  i = j+1;
  }
  SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
  req.ContentLength = SomeBytes.Length;
  Stream newStream = req.GetRequestStream();
  newStream.Write(SomeBytes, 0, SomeBytes.Length);
  newStream.Close();
  }
  else
  {
  req.ContentLength = 0;
  }
  
  
  res = (HttpWebResponse)req.GetResponse();
  cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));
  HttpContext.Current.Application.Lock();
  HttpContext.Current.Application["cookieheader"] = cookieheader;
  HttpContext.Current.Application.UnLock();
  
  Stream ReceiveStream = res.GetResponseStream();
  Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
  StreamReader sr = new StreamReader( ReceiveStream, encode );
  Char[] read = new Char[256];
  int count = sr.Read( read, 0, 256 );
  while (count > 0)
  {
  String str = new String(read, 0, count);
  strResult += str;
  count = sr.Read(read, 0, 256);
  }
  }
  catch(Exception e)
  {
  strResult = e.ToString();
  }
  finally
  {
  if ( res != null )
  {
  res.Close();
  }
  }
  
  return strResult;
  }
  
  
  public static string getPage(String url, String paramList)
  {
  HttpWebResponse res = null;
  string strResult = "";
  
  try
  {
  
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  req.Method = "POST";
  req.KeepAlive = true;
  req.ContentType = "application/x-www-form-urlencoded";
  CookieContainer cookieCon = new CookieContainer();
  req.CookieContainer = cookieCon;
  req.CookieContainer.SetCookies(new Uri(url),cookieheader);
  StringBuilder UrlEncoded = new StringBuilder();
  Char[] reserved = {'?', '=', '&'};
  byte[] SomeBytes = null;
  
  if (paramList != null)
  {
  int i=0, j;
  while(i<paramList.Length)
  {
  j=paramList.IndexOfAny(reserved, i);
  if (j==-1)
  {
  UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
  break;
  }
  UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
  UrlEncoded.Append(paramList.Substring(j,1));
  i = j+1;
  }
  SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
  req.ContentLength = SomeBytes.Length;
  Stream newStream = req.GetRequestStream();
  newStream.Write(SomeBytes, 0, SomeBytes.Length);
  newStream.Close();
  }
  else
  {
  req.ContentLength = 0;
  }
  
  
  res = (HttpWebResponse)req.GetResponse();
  Stream ReceiveStream = res.GetResponseStream();
  Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
  StreamReader sr = new StreamReader( ReceiveStream, encode );
  Char[] read = new Char[256];
  int count = sr.Read( read, 0, 256 );
  while (count > 0)
  {
  String str = new String(read, 0, count);
  strResult += str;
  count = sr.Read(read, 0, 256);
  }
  }
  catch(Exception e)
  {
  strResult = e.ToString();
  }
  finally
  {
  if ( res != null )
  {
  res.Close();
  }
  }
  
  return strResult;
  }
  
  
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
  //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
  InitializeComponent();
  base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
  this.Load += new System.EventHandler(this.Page_Load);
  
  }
  #endregion
  
  
  
  }
  }
//通过Post发送的数据
   string payload="chkbook=book&keyword=管理";
   WebRequest req = WebRequest.Create("http://localhost/pceo/Search.aspx");
   req.Method = "POST";
   req.ContentType = "application/x-www-form-urlencoded";
   StringBuilder UrlEncoded = new StringBuilder();
   Char[] reserved = {'?', '=', '&'};
   byte[] SomeBytes = null;
   if (payload != null)
   {
   int i=0, j;
   while(i<payload.Length)
   {
   j=payload.IndexOfAny(reserved, i);
   if (j==-1)
   {
   UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, payload.Length-i),System.Text .Encoding .GetEncoding ("gb2312")));
   break;
   }
   UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, j-i),System.Text .Encoding .GetEncoding ("gb2312")));
   UrlEncoded.Append(payload.Substring(j,1));
   i = j+1;
   }
   SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
   req.ContentLength = SomeBytes.Length;
   Stream newStream = req.GetRequestStream();
   newStream.Write(SomeBytes, 0, SomeBytes.Length);
   newStream.Close();
   }
   else
   {
   req.ContentLength = 0;
   }
   try
   {
   WebResponse result = req.GetResponse();
   Stream ReceiveStream = result.GetResponseStream();
  
   Byte[] read = new Byte[512];
   int bytes = ReceiveStream.Read(read, 0, 512);
  
   txtHTML.InnerHtml = "";
   while (bytes > 0)
   {
  
   // 注意:
   // 下面假定响应使用 UTF-8 作为编码方式。
   // 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
   // Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
   Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
   txtHTML.InnerHtml = txtHTML.InnerHtml + encode.GetString(read, 0, bytes);
   bytes = ReceiveStream.Read(read, 0, 512);
   }
   }
   catch(Exception)
   {
   txtHTML.InnerHtml = "检索页时出错";
   }
最近有个朋友离开IT行业二年的朋友说要实现用程序向某个网站的页面上传数据,他是意思是每天有几十条数据要在网站页面上填写,很烦,最好用程序来写。网站页面是用POST传递的,同时没有验证码之类的东东,只有一点限制就是5分种内不能填写二次记录。这一切都好办。
  
  using System.Web;
  using System.Net;
  using System.Text;
  using System.IO;
  
  //创建对某个网站页面的请求
  
  HttpWebRequest myRequest = (HttpWebRequest )WebRequest.Create("http://www.knowsky.com/a.asp")
  
  //上传的数据,”TextBox1“这些东东是网站页面里的控件ID,如果要上传多个值也是用&来分隔
  
   string postData="TextBox1="+this.textBox1.Text+"&TextBox2="+this.textBox2.Text+"
  &TextBox3="+this.textBox3.Text+"&TextBox4="+this.textBox4.Text;
   ASCIIEncoding encoding=new ASCIIEncoding();
   byte[] byte1=encoding.GetBytes(postData);//最终编码后要上传的数据
   // Set the content type of the data being posted.
   myRequest.ContentType="application/x-www-form-urlencoded";
   myRequest.Method="post";//post上传方式
   // Set the content length of the string being posted.
   myRequest.ContentLength=postData.Length;
   Stream newStream=myRequest.GetRequestStream();
   newStream.Write(byte1,0,byte1.Length);
  
  
  一切就OK了,如果你想上传后看到网站的内容的话,可以在程序里放一个IE控件,使用
  
  axWebBrowser1.Navigate("http://www.knowsky.com/a.asp");
  axWebBrowser1.Refresh2();

转载于:https://www.cnblogs.com/hq2008/archive/2007/12/24/1012504.html

asp.net httprequest httpresponse相关推荐

  1. ASP.NET Core 性能优化最佳实践

    本文提供了 ASP.NET Core 的性能最佳实践指南. 译文原文地址:https://docs.microsoft.com/en-us/aspnet/core/performance/perfor ...

  2. 写一个简版 asp.net core

    动手写一个简版 asp.net core Intro 之前看到过蒋金楠老师的一篇 200 行代码带你了解 asp.net core 框架,最近参考蒋老师和 Edison 的文章和代码,结合自己对 as ...

  3. ASP.NET Core HTTP 管道中的那些事儿

    前言 马上2016年就要过去了,时间可是真快啊. 上次写完 Identity 系列之后,反响还不错,所以本来打算写一个 ASP.NET Core 中间件系列的,但是中间遇到了很多事情.首先是 NPOI ...

  4. 用Asp.net写自己的服务框架

    用Asp.net写自己的服务框架 阅读目录 开始 理解Asp.net管线 HttpHandler HttpModule 关于Content-Encoding的解释 选 HttpHandler 还是 H ...

  5. ASP.NET五大核心对象解析

    转载地址:http://www.hello-code.com/blog/asp.net/201408/3841.html 想当初在只使用WebForms框架并以服务端为中心的开发模式时,发现Asp.n ...

  6. 我心目中的Asp.net核心对象

    想当初在只使用WebForms框架并以服务端为中心的开发模式时,发现Asp.net好复杂.一大堆服务端控件,各有各的使用方法, 有些控件的事件也很重要,必须在合适地时机去响应,还真有些复杂.后来逐渐发 ...

  7. ASP.NET MVC框架(第一部分)

    [原文地址]ASP.NET MVC Framework (Part 1) [原文发表日期] Tuesday, November 13, 2007 3:45 AM 两个星期前, 我在博客里讨论了ASP. ...

  8. 从.Net类库代码来看Asp.net运行时(转自酷网动力)

    写在前面的话:网上讲Asp.net运行模式的好文章已经很多了,笔者本不用多此一举,另成一文.但从笔者自己的学习经验看,如果学到的这些知识不能对应 到类库中的源代码,印象总归不够深刻,大有隔靴搔痒之感. ...

  9. 一步步完成“迷你版” 的ASP.NET Core框架

    一 前言 Artech 分享了 200行代码,7个对象--让你了解ASP.NET Core框架的本质 . 用一个极简的模拟框架阐述了ASP.NET Core框架最为核心的部分. 这里一步步来完成这个迷 ...

最新文章

  1. Python基础总结(3)
  2. mysqlhelper
  3. 土人系列AS入门教程--实战篇
  4. NOIP 2017 总结
  5. oracle10 监听日志,windows 清空oracle的监听日志listener.log
  6. 通过xrdp实现远程桌面连接Windows Azure linux虚拟机
  7. python读取print输出的内容_Python文件中将print的输出内容重定向到变量中
  8. 基于PHP以及JQUERY AJAX的计算器实例
  9. java ee 企业级意味着什么意思_​Java EE是什么意思
  10. supervisor 管理
  11. 367.有效的完全平方数   (力扣leetcode) 博主可答疑该问题
  12. 斜齿轮重合度计算公式_斜齿轮的端面重合度计算
  13. C# 使用RestSharp库实现POST请求
  14. crr树不同步数期权定价 matlab,CRR二叉树模型和例题.doc
  15. 百度富文本编辑器配置使用
  16. Cocos2d-x学习笔记(五)仿真树叶飘落效果的实现(精灵旋转、翻转、钟摆运动等综合运用)
  17. 如何通过样本数据推断其分布
  18. 计算机应用中的CAI,使用计算机来进行翻译属于计算机应用领域中的()。A.AIB.CAEC.CADD.CAI...
  19. ccsa安学网小程序_CCSA安学网题库及答案
  20. 交流电计算方法c语言,正弦交流电的计算公式

热门文章

  1. Spring Boot集成Swagger
  2. SpringMVC处理异常
  3. [编转]Android localsocket 的基础和使用实践: 02
  4. java resultset 赋值_ResultSet数据自动绑定到JavaBean中 | 学步园
  5. 计算机的代表性产品,电脑展回顾 十款最具代表性存储产品
  6. php解escape,PHP下escape解码函数用法示例
  7. 矩阵连乘问题算法思想_AI自然语言处理算法岗常见面试题(一)
  8. python 去重_上来就情感分析?我还是先用python去去重吧!
  9. python系统提供构造函数传入参数_python类变量与构造函数的使用
  10. java invoke int long,将Long转换为Integer