尝试使用HttpWebRequest&登录网站HttpWebResponse抛出错误

时间:2017-12-19 20:09:42

标签: c# httpwebrequest httpwebresponse

所以我目前正在学习HttpWebRequests&回应是因为我喜欢为我自动化在线工作的想法。 因此,在阅读了一些关于它之后,我决定从一些简单的事情开始,也许登录到一个网站,因为这是我经常做的事情。 我决定尝试使用Spotify,因为网站简单明了,我认为这是一个很好的起点。

所以我到目前为止的是这个,但我一直收到错误

  

System.Net.WebException:'远程服务器返回错误:(405)   方法不允许。'

尝试登录时是否应该遵循一系列特定步骤?我在找什么?我用fiddler来获取postData参数(不确定那些是不是正确的,我想我还需要更多) 如果我错过了任何步骤,请随时告诉我我在这里做错了什么。

protected static CookieContainer Login()
        {
            string userName = "myUsername";
            string password = "myPassword";

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "username=" + userName + "&password=" + password;
            byte[] postDataBytes = encoding.GetBytes(postData);

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://accounts.spotify.com/en-EN/login");

            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = postDataBytes.Length;
            httpWebRequest.AllowAutoRedirect = false;

            using (var stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(postDataBytes, 0, postDataBytes.Length);
                stream.Close();
            }

            var cookieContainer = new CookieContainer();
//This is where it throws the error
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    foreach (Cookie cookie in httpWebResponse.Cookies)
                    {
                        cookieContainer.Add(cookie);
                    }
                }
            }

            return cookieContainer;
        }

0 个答案:

没有答案