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. Android linux kernel privilege escalation vulnerability and exploit (CVE-2014-4322)

    In this blog post we'll go over a Linux kernel privilege escalation vulnerability I discovered which ...

  2. excel批量取消隐藏工作表

    按下"Alt+F11"键,在打开的"Microsoft Bisual Basic"窗口中,选择"插入——模块".,复制下面的代码,按F5键运 ...

  3. Wireshark 与 Tcpdump

    [1]Wireshark 与 Tcpdump Wireshark是Windows下非常容易上手的抓包工具.但在Linux下很难找到一个好用的图形界面抓包工具.还好有Tcpdump.我们可以用Tcpdu ...

  4. systemctl使用说明

    # systemctl #输出已激活单元 # systemctl list-units #输出已激活单元 # systemctl --failed #输出运行失败的单元 # systemctl lis ...

  5. C# .Net 下 x86使用大内存的处理

    /LARGEADDRESSAWARE 选项通知链接器应用程序可处理大于 2 GB 的地址. 在 64 位编译器中,默认情况下启用此选项. 在 32 位编译器中,如果未在链接器行上指定 /LARGEAD ...

  6. android中实现毛笔效果(View 中画图)

    近期有一个项目设计一个APP实现通过触摸屏实现毛笔写字效果.传统的绘画板程序直接通过Path的moveTo和LineTo便可实现简单的线条绘画程序.然而要达到毛笔的笔锋效果则须要更为具体点的设计.我的 ...

  7. React Native安装步骤

    先贴出中文网安装指南:http://reactnative.cn/docs/0.46/getting-started.html 本文会点出一些安装时遇到的坑,和解决方案! 1.首先是安装Chocola ...

  8. Linux 技巧:让进程在后台运行的可靠方法

    原文链接:http://www.ibm.com/developerworks/cn/linux/l-cn-nohup/ 想让进程在断开连接后依然保持运行?如果该进程已经开始运行了该如何补救? 如果有大 ...

  9. Myecplise Tomcat 启动很慢

    今天突然遇到一个问题,tomcat在Myecplse启动非常慢,直接用tomcat自带的start.bat启动很快,如果通过Myeclipse启动会发现项目一直在实例化,最后发现是因为加了断点调试,断 ...

  10. sudo npm install -g cnpm --registry=https://registry.npm.taobao.org