C#使用HttpWebRequest實現標準HTTP POST和POST to AJAX『is_ajax_request()』的PHP登錄函數

C#使用HttpWebRequest實現標準HTTP POST和POST to AJAX『is_ajax_request()』的PHP登錄函數

C#使用HttpWebRequest實現標準HTTP POST和POST to AJAX『is_ajax_request()』的PHP登錄函數

 

        public String loginPHP(String PHPName, String StrUserName, String StrPassword)
        {
            string url = m_StrDomain + PHPName;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = “POST”;

            //–
            //request.ContentType = “application/x-www-form-urlencoded”;//一般POST
            request.ContentType = “application/json; charset=UTF-8”;//POST to AJAX [is_ajax_request()]
            request.Accept = “application/json, text/javascript”;//POST to AJAX [is_ajax_request()]
            request.UserAgent = “”;//POST to AJAX [is_ajax_request()]
            request.Headers.Add(“X-Requested-With”, “XMLHttpRequest”);//POST to AJAX [is_ajax_request()]
            //–

            request.CookieContainer = m_CookieContainer;
            string user = StrUserName; //用户名
            string pass = StrPassword; //密码

            //–
            //string data = “username=” + HttpUtility.UrlEncode(user) + “&password=” + HttpUtility.UrlEncode(pass);//一般POST
            string data = String.Format(“\”account\”:\”{0}\”, \”password\”:\”{1}\””, StrUserName, StrPassword);//POST to AJAX [is_ajax_request()]
            data = “{” + data + “}”;//POST to AJAX [is_ajax_request()]
            //–
            
            request.ContentLength = data.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
            writer.Write(data);
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = “UTF-8”; //默认编码
            }

            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            data = reader.ReadToEnd();

            m_CookieContainer = request.CookieContainer;
            response.Close();

            return data;
        }

 

 

 

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *