Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

winforms - C# WebClient Log onto Website

I'm trying to log onto a website by providing my (correct) username and password.

Here's the code:

        string URL = @"https://www.t-mobile.co.uk/service/your-account/login/";

        string username = "a_user";
        string password = "a_password";
        //ServicePointManager.Expect100Continue = false;

        CookieAwareClient client = new CookieAwareClient();


        NameValueCollection postData = new NameValueCollection();
        postData.Add("username", username);
        postData.Add("password", password);

        byte[] response = client.UploadValues(URL,  postData);

        ASCIIEncoding enc = new ASCIIEncoding();
        string Source = enc.GetString(response);

But, surprise surprise, it's not logging on. I just get the logon page back.

Any help would be appreciated and this is doing my head in now!!

Thanks, Jim

For completeness here is my WebClient class -

public class CookieAwareClient : WebClient
{
    private CookieContainer m_container = new CookieContainer();
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = m_container;
        }
        return request;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is posted on server if you try to login in browser:

org.apache.struts.taglib.html.TOKEN=81243ce1a02ff285745f7c25b86234a9&showLogin=true&upgrade=&username=username&password=password&submit=Log+in

Try adding those values as well, and figure out how TOKEN is generated.

EDIT: Check if cookies that page gives you are submited back too.

ANOTHER EDIT: Too see what is going on between server and browser (=Firefox) when you are making a request or posting data use LiveHttpHeaders addon.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...