public class HTMLHelper
    {
        /// <summary>   
        /// 获取CooKie  
        /// /// </summary>
        /// /// <param name="loginUrl"></param>   
        /// /// <param name="postdata"></param>   
        /// /// <param name="header"></param>  
        /// /// <returns></returns>      
        public static CookieContainer GetCooKie(string loginUrl, HttpHeader header)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                CookieContainer cc = new CookieContainer();
                request = (HttpWebRequest)WebRequest.Create(loginUrl);
                request.Method = "GET";
                request.ContentType = header.contentType;
              
                 
                request.AllowAutoRedirect = false;
                request.CookieContainer = cc;
                request.KeepAlive = true;
                
                //接收响应        
                response = (HttpWebResponse)request.GetResponse();
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                CookieCollection cook = response.Cookies;               //Cookie字符串格式    
                string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);
                return cc;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

/// <summary>   
        /// 获取CooKie  
        /// /// </summary>
        /// /// <param name="loginUrl"></param>   
        /// /// <param name="postdata"></param>   
        /// /// <param name="header"></param>  
        /// /// <returns></returns>      
        public static CookieContainer GetCooKie(string loginUrl, string postdata, HttpHeader header)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                CookieContainer cc = new CookieContainer();
                request = (HttpWebRequest)WebRequest.Create(loginUrl);
                request.Method = header.method;
                request.ContentType = header.contentType;
                byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata);
                request.ContentLength = postdatabyte.Length;
                request.AllowAutoRedirect = false;
                request.CookieContainer = cc;
                request.KeepAlive = true;
                //提交请求      
                Stream stream;
                stream = request.GetRequestStream();
                stream.Write(postdatabyte, 0, postdatabyte.Length);
                stream.Close();
                //接收响应        
                response = (HttpWebResponse)request.GetResponse();
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                CookieCollection cook = response.Cookies;               //Cookie字符串格式    
                string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);
                return cc;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取html  
        /// </summary>  
        /// <param name="getUrl"></param>   
        /// <param name="cookieContainer"></param>  
        /// <param name="header"></param>    
        /// <returns></returns>

public static string GetHtml(string getUrl, CookieContainer cookieContainer, HttpHeader header)
        {
            Thread.Sleep(1000);
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = header.contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
                httpWebRequest.Referer = getUrl;
                httpWebRequest.Accept = header.accept;
                httpWebRequest.UserAgent = header.userAgent;
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
                return html;
            }
            catch (Exception e)
            {
                if (httpWebRequest != null) httpWebRequest.Abort();
                if (httpWebResponse != null) httpWebResponse.Close();
                return string.Empty;
            }
        }

/// <summary>
        /// 获取html  
        /// </summary>  
        /// <param name="getUrl"></param>   
        /// <param name="cookieContainer"></param>  
        /// <param name="header"></param>    
        /// <returns></returns>

public static string GetHtml(string getUrl,string post, CookieContainer cookieContainer, HttpHeader header,Encoding en)
        {
            Thread.Sleep(1000);
            HttpWebRequest myHttpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {               
                byte[] oneData = Encoding.Default.GetBytes(post);
                Uri uri = new Uri(getUrl);
                myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri);//请求的URL
                myHttpWebRequest.CookieContainer = cookieContainer;//*发送COOKIE
                myHttpWebRequest.Method = header.method;
                myHttpWebRequest.ContentType = header.contentType;
                myHttpWebRequest.ContentLength = oneData.Length;
                Stream newMyStream = myHttpWebRequest.GetRequestStream();
                newMyStream.Write(oneData, 0, oneData.Length);

try
                {
                    httpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), en);

string str = sr.ReadToEnd();

string msg = string.Empty;

return str;
                }
                catch (Exception ex)
                {
                    return string.Empty;
                }
            }
            catch (Exception e)
            {
                if (myHttpWebRequest != null) myHttpWebRequest.Abort();
                if (httpWebResponse != null) httpWebResponse.Close();
                return string.Empty;
            }
            return string.Empty;
        }

/// <summary>
        /// 获取html  
        /// </summary>  
        /// <param name="getUrl"></param>   
        /// <param name="cookieContainer"></param>  
        /// <param name="header"></param>    
        /// <returns></returns>

public static string GetHtml(string getUrl, string post, CookieContainer cookieContainer,out CookieContainer co, HttpHeader header, Encoding en)
        {
            Thread.Sleep(1000);
            HttpWebRequest myHttpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            co = new CookieContainer();
            try
            {
                byte[] oneData = Encoding.Default.GetBytes(post);
                Uri uri = new Uri(getUrl);
                myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri);//请求的URL
                if (cookieContainer.Count > 0)
                {
                    myHttpWebRequest.CookieContainer = cookieContainer;
                }
                else
                {
                    myHttpWebRequest.CookieContainer = co;
                }
                
                myHttpWebRequest.Method = header.method;
                myHttpWebRequest.ContentType = header.contentType;
                myHttpWebRequest.ContentLength = oneData.Length;
                Stream newMyStream = myHttpWebRequest.GetRequestStream();
                newMyStream.Write(oneData, 0, oneData.Length);

try
                {
                    httpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), en);

httpWebResponse.Cookies = myHttpWebRequest.CookieContainer.GetCookies(myHttpWebRequest.RequestUri);
                    CookieCollection cook = httpWebResponse.Cookies;               //Cookie字符串格式    
                    string strcrook = myHttpWebRequest.CookieContainer.GetCookieHeader(myHttpWebRequest.RequestUri);

string str = sr.ReadToEnd();

string msg = string.Empty;

return str;
                }
                catch (Exception ex)
                {
                    return string.Empty;
                }
            }
            catch (Exception e)
            {
                if (myHttpWebRequest != null) myHttpWebRequest.Abort();
                if (httpWebResponse != null) httpWebResponse.Close();
                return string.Empty;
            }
            return string.Empty;
        }

/// <summary>
        /// 获取Stream  
        /// </summary>  
        /// <param name="getUrl"></param>   
        /// <param name="cookieContainer"></param>  
        /// <param name="header"></param>    
        /// <returns></returns>

public static Stream GetStream(string getUrl, CookieContainer cookieContainer, HttpHeader header)
        {
            Thread.Sleep(1000);
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType = header.contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
                httpWebRequest.Referer = header.referer;
                httpWebRequest.Accept = header.accept;
                httpWebRequest.UserAgent = header.userAgent;
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();

return responseStream;
            }
            catch (Exception e)
            {
                if (httpWebRequest != null) httpWebRequest.Abort();
                if (httpWebResponse != null) httpWebResponse.Close();
                return null;
            }
        }
     
        public static Stream GetStream(string getUrl, CookieContainer cookieContainer, out CookieContainer co, HttpHeader header)
        {

Thread.Sleep(1000);
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            co = new CookieContainer();
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                if (cookieContainer.Count > 0)
                {
                    httpWebRequest.CookieContainer = cookieContainer;
                }
                else
                {
                    httpWebRequest.CookieContainer = co;
                }
               
                httpWebRequest.ContentType = header.contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
                httpWebRequest.Referer = getUrl;
                httpWebRequest.Accept = header.accept;
                httpWebRequest.UserAgent = header.userAgent;
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();

httpWebResponse.Cookies = httpWebRequest.CookieContainer.GetCookies(httpWebRequest.RequestUri);
                CookieCollection cook = httpWebResponse.Cookies;               //Cookie字符串格式    
                string strcrook = httpWebRequest.CookieContainer.GetCookieHeader(httpWebRequest.RequestUri);

return responseStream;
            }
            catch (Exception e)
            {
                if (httpWebRequest != null) httpWebRequest.Abort();
                if (httpWebResponse != null) httpWebResponse.Close();
                return null;
            }
        }

}

public class HttpHeader
    {
        public string contentType { get; set; }
        public string accept { get; set; }
        public string userAgent { get; set; }
        public string method { get; set; }
        public int maxTry { get; set; }
        public string referer { get; set; }
    }

C#实现网站登录的更多相关文章

  1. cookielib和urllib2模块相结合模拟网站登录

    1.cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用 本模块的CookieJar类的对 ...

  2. discuz论坛与其它网站登录注册整合

    discuz论坛与其它网站登录注册整合 本文以discuz 7.0.0 php版本的论坛与 .net 2.0的网站注册登录整合为类.没有采用uc_center或第三方插件.以另类的方式实现.此方法实现 ...

  3. Java模拟网站登录02【转载】

    如何用Java代码模拟一些如百度.QQ之类的网站登录?有两个方式,一是发送模拟请求,二是模拟浏览器操作,而这两种方式恰好在Java有开源实现,在这里介绍一个工具包,它是家喻户晓的HttpClient. ...

  4. c# winform实现网页上用户自动登陆,模拟网站登录

    using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO ...

  5. 搭建开发框架Express,实现Web网站登录验证

    NodeJS学习笔记(一)——搭建开发框架Express,实现Web网站登录验证   JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需 ...

  6. Javascript技巧实例精选(4)—FTP网站登录的Javascript实现

    FTP网站登录的Javascript实现 >>点击这里下载完整html源码<< 这是最后的截图 这是核心Javascript源码 function goFtpSite() { ...

  7. 关于网站登录后的页面操作所携带的不同cookie值

    对于课堂派网站,登录后的页面操作只需要携带PHPSESSID或者cookie中间那部分即可,两个都带也可,SERVERID不知道是干啥的,每次响应的都会变. 代码实现: cookie = None c ...

  8. windowsXP用户被禁用导致不能网站登录

    1.查看系统事件,发现弹出如下的错误 2.根据上面的错误,我们很容易就可以判断是禁用了账户引起的 2.1后面进入计算机管理,再进入用户管理 2.2双击点开Internet来宾用于,发现此用户已经停用了 ...

  9. SharePoint 网站登录不上,3次输入用户名/密码白页

    新搭建的SharePoint 2013环境,第一次干的这么憋屈的慌,先是接了一个Ghost的服务器,装好的服务器.Sql.SharePoint.VS等一系列,却发现怎么都登陆不上去,输入账号3次以后白 ...

  10. HttpClient 4.x 执行网站登录并抓取网页的代码

    HttpClient 4.x 的 API 变化还是很大,这段代码可用来执行登录过程,并抓取网页. HttpClient API 文档(4.0.x), HttpCore API 文档(4.1) pack ...

随机推荐

  1. 出租车Jt/T 905协议与部标1078协议融合的网约车视频监控平台

    出租车jt/t 905协议,是jt/t 808协议的一个变种,设计者将部标808协议拿过来,并不是单纯的增加网约车相关的指令集,而且对原有的指令如定位0×0200指令也进行了修改,经过一通剧烈的修改, ...

  2. nl 命令

    nl命令在linux系统中用来计算文件中行号.nl 可以将输出的文件内容自动的加上行号!其默认的结果与 cat -n 有点不太一样, nl 可以将行号做比较多的显示设计,包括位数与是否自动补齐 0 等 ...

  3. 403/you don't have the permission to access on this server

    Localhost/index.php出现 错误403 you don't have the permission to access on this server 现在已经解决,特将方法与大家分享. ...

  4. 安装wamp后 异常Exception Exception in module wampmanager.exe at 000F15A0

    系统环境:Windows 2008 R2 64bit 安装环境:wampserver2.4-x64 按照正常windows安装程序,完成WAMP Server程序安装,安装完成启动WAMP Serve ...

  5. linux 参数内核

    优化Linux内核参数   转自:http://www.centoscn.com/CentOS/config/2013/0804/992.html vim /etc/sysctl.conf 1.net ...

  6. 【Atheros】pktgen的ipv6地址处理函数参考及ipv6基本知识

    pktgen有很多函数可以作为很好的网络相关的工具函数,这里列出ipv6中1:0:0:0:0:0:0:1和1::1这两种地址形式相互转化的工具函数. 第一个函数,用于把一个1:0:0:0:0:0:0: ...

  7. wordcloud使用

    学了下怎么用wordcloud. 以imet的数据集为例 https://www.kaggle.com/c/imet-2019-fgvc6 读取“train.csv”,”label.csv”文件,得到 ...

  8. ios推送服务,php服务端

    本文转载至http://my.oschina.net/AStar/blog/176531   生成证书 证书生成参考:https://parse.com/tutorials/ios-push-noti ...

  9. 【BZOJ4894】天赋 有向图生成树计数

    [BZOJ4894]天赋 Description 小明有许多潜在的天赋,他希望学习这些天赋来变得更强.正如许多游戏中一样,小明也有n种潜在的天赋,但有一些天赋必须是要有前置天赋才能够学习得到的.也就是 ...

  10. Office Web Apps Server 2013与PDF(二)

    在上一篇文章(Office Web Apps Server 2013与PDF(一))中,曾经介绍了Office Web Apps Server 2013在更新后,可以直接对PDF文档进行在线的查看.不 ...