.net 模擬登陸 post https 請求跳轉頁面

無覺發表於2015-04-30

AllowAutoRedirect property is true, the Referer property is set automatically when the request is redirected to another site.">如果 AllowAutoRedirect 屬性為 true,則 Referer 屬性在請求被重定向到另一個站點時自動設定。

Referer HTTP header, set the Referer property to null.">若要清除 RefererHTTP 標頭,請將 Referer 屬性設定為 null
如果設定了  Referer 則 指定到某個站點. 被這東西小坑了一下 漲姿勢。

 

 

          private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
          {
               return true; //總是接受安全證書
          }

          private void test() 
          {
               ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
               CookieCollection _cookies = null; //後續使用
               var addRess = "https://xxxxxxxxxx";
               var data = "account=xxxxxxx&password=xxxxx";

               HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addRess);
               request.CookieContainer = new CookieContainer();
               request.Timeout = 1000 * 60;
               request.Method = "POST";               
               request.ContentType = "application/x-www-form-urlencoded";
               request.AllowAutoRedirect = true;
               request.Referer = addRess;

               byte[] bs = Encoding.UTF8.GetBytes(data);
               HttpWebResponse response = null;
               StreamReader myStreamReader = null;
               Stream myRequestStream = null;
               request.ContentLength = bs.Length;
               string retString = string.Empty;
               try
               {
                    using (myRequestStream = request.GetRequestStream())
                    {
                         myRequestStream.Write(bs, 0, bs.Length);
                         myRequestStream.Close();
                    }
                    response = (HttpWebResponse)request.GetResponse();
                    _cookies = response.Cookies;
                    using (Stream myResponseStream = response.GetResponseStream())
                    {
                         using (myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("BIG5")))
                         {
                              retString = myStreamReader.ReadToEnd();
                         }
                    }
               }
               catch (Exception)
               {

                    throw;
               }
               finally
               {
                    if (myRequestStream != null)
                    {
                         myRequestStream.Close();
                    }
                    if (response != null)
                    {
                         response.Close();
                    }
                    if (myStreamReader != null)
                    {
                         myStreamReader.Close();
                    }
               }
          }

 

相關文章