C# 处理302后获取COOKIE

来源:互联网 发布:ip网络报警器 编辑:程序博客网 时间:2024/05/29 04:20
 

C# 处理302后获取COOKIE

分类: 1007人阅读 评论(0) 收藏 举报
c#string.netexceptioncookiesstream

public static string Login(String url, String paramList, string MyEncode, ref string myCookieContainer,string refer)
{
    HttpWebResponse res = null;
    string strResult = string.Empty; ;
    try
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET4.0C; .NET4.0E; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
        if (!string.IsNullOrEmpty(refer))
        {
            req.Referer = refer;
        }
        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();

        //MessageBox.Show(((int)res.StatusCode)+"");
        
        myCookieContainer = req.CookieContainer.GetCookieHeader(new Uri(url));
        if (res.StatusCode == HttpStatusCode.Redirect)
        {
            //MessageBox.Show(res.Headers["Location"]);
            string cookies = res.Headers["Set-Cookie"].Replace(",", "%2c");
            cookies = cookies.Replace("httponly%2c", "");
            //MessageBox.Show(cookies);
            return SendDataByGet(res.Headers["Location"], "", "utf-8", cookies, refer);
        }
        
        Stream ReceiveStream = res.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding(MyEncode);
        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)
    {
        //MessageBox.Show(e.ToString());
        throw new Exception("Web.Login:/r/n" + e.ToString());
    }
    finally
    {
        if (res != null)
        {
            res.Close();
        }
    }
    return strResult;
}



public static string SendDataByGet(string url, string data, string encode, string cookies, string refer)
{
    string retString = string.Empty;
    HttpWebResponse response = null;
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : "?") + data);
        string host = string.Empty;
        Uri uri = new Uri(url);
        host = uri.Scheme + "://" + uri.Authority + "/";
        CookieContainer cc = new CookieContainer();
        string[] SegCookie = new string[] { };
        SegCookie = cookies.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < SegCookie.Length; i++)
        {
            string[] tmp = new string[] { };
            tmp = SegCookie[i].Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
            if (tmp.Length == 2)
            {
                Cookie c = new Cookie();
                c.Name = tmp[0].Trim();
                c.Value = tmp[1];
                cc.Add(new Uri(host), c);
            }
        }
        request.CookieContainer = cc;

        request.Method = "GET";
        request.ContentType = "text/html;charset=" + encode;
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET4.0C; .NET4.0E; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
        if (!string.IsNullOrEmpty(refer))
        {
            request.Referer = refer;
        }
        else
        {
            request.Referer = url;
        }
        response = (HttpWebResponse)request.GetResponse();

        string abc = string.Empty;
        for (int i = 0; i < response.Headers.Count; i++)
        {
            abc += response.Headers.Keys[i].ToString() + "=====>" + response.Headers[response.Headers.Keys[i].ToString()]+"/r/n";
        }
        //MessageBox.Show(abc);

        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encode));
        retString = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        myResponseStream.Close();
        request.Abort();
        response.Close();
        return retString;
    }
    catch (Exception ex) { throw new Exception("Web.SendDataByGet:/r/n" + ex.ToString()); }
    finally
    {
        if (response != null)
            response.Close();
    }

}

原创粉丝点击