简体   繁体   中英

How can I send a login request to a website?

so I want to send a request to log in to a website, how can I do that

I have tried the code bellow:

string formUrl = "https://account.mojang.com/login";
            string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
            string cookieHeader;
            WebRequest req = WebRequest.Create(formUrl);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "GET";
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];

I get an error at line 9 : "Can not send a body of content with this type of verb."

I will answer this question in two parts: first the error message that you have received, and secondly how you should solve the problem.

Your error message resulted from line 9, evidently req.GetRequestStream() has failed for some reason:

using (Stream os = req.GetRequestStream())

Looking closer at the text of the message, it is evident what the problem is - you are trying to send a x-form-urlencoded message body with a GET request when this is not supported by the WebRequest implementation.

Can not send a body of content with this type of verb.

The function of GetRequestStream() is to get a stream to which you can write a request body (a "body of content"), in your case the login parameters. You are sending a GET request (GET and POST are referred to as "verbs" in the HTTP specification), and WebRequest does not support this.

Going back to the actual problem here, I believe that you did not mean to send a GET request and need to send a POST request intead. If that is the case then you simply need to change line 6 to read:

req.Method = "POST";

Most login services expect POST requests and GET requests do not work in any case. However, if you wanted to do a GET request with data using WebRequest you need to do it in a different way. The data must be encoded into the initial URL and there is no need to get a request stream or write to it. The fixed code in that case would read:

            string formURL = string.Format("https://account.mojang.com/login?email_address={0}&password={1}", "your email", "your password");
            string cookieHeader;
            WebRequest req = WebRequest.Create(formUrl);
            req.Method = "GET";
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM