c#控制台實現post網站登錄


如題,首先我寫了一個web頁面來實現post登陸,只做演示,代碼如下

 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name = context.Request.Params["username"];
            
            if (name == "1")
            {
                context.Response.Write("ok");
            }
            else
            {
                context.Response.Write("no");
            }
       
        }

只要name是1就ok否則no

簡潔說下Get和post  get通過在網絡地址中附加參數來完成數據的提交,可以在url地址中看到,而post則是在頁面內容中填寫參數來完成提交  F12看一下就是username=1&userpwd=1這種格式的, POST 中文數據的時候,先中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。

然后控制台模擬一下  HttpWebRequest  HttpWenResponse

HttpWebRequest類主要利用Http協議來和服務器交互,在Method中指定提交方式,GET或者POST

代碼如下

 static void Main(string[] args)
        {
            string name = "1";
            string postdata = "username=" + name;
            byte[] data = Encoding.UTF8.GetBytes(postdata);
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:8022/login.ashx");
            webrequest.Method = "POST";
            webrequest.ContentType = "application/x-www-form-urlencoded";
            webrequest.ContentLength = data.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader sr = new StreamReader(webresponse.GetResponseStream(), Encoding.UTF8);
            string s = sr.ReadToEnd();
            Console.WriteLine(s);
        }

  結果自然ok  當把name改為2結果為no滿足需求

當然這只是一個很簡單的模擬,也就是試驗一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM