利用HttpRequest登录到某个网站,然后获取网站信息的
题目:有的网站的相干内容必需要在登录后才可以检察,其登录信息保存在session变量之中。这样,利用asphttp等组件就难以正确失掉所要的信息。
办理:利用asp.net中的httprequest和httpresponse来实现。
要点:
1。 经过附加一个cookiecontainer到httprequest工具中,可以失掉登录后前往的代表SESSION ID的COOKIE。 见Login要领
2。 将此COOKIE包罗在一个cookiecontainer中并附加到另一个HTTPREQUEST恳求中,则可以实现SESSION的复原。见getPage要领
源程序如下:
getHttpInfo.aspx:
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 description for WebForm1.
///
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{
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;
}
- 文章作者: 福州军威计算机技术有限公司
军威网络是福州最专业的电脑维修公司,专业承接福州电脑维修、上门维修、IT外包、企业电脑包年维护、局域网网络布线、网吧承包等相关维修服务。
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 、作者信息和声明。否则将追究法律责任。
TAG:
评论加载中...
|