C#UWP使用cookie登录网站

时间:2017-07-22 10:37:46

标签: c# wpf uwp httpclient webclient

我正在尝试将WPF应用程序转换为UWP,但我还想知道如何让这个应用程序正常工作。

WPF应用程序连接到网站,获取cookie,从html读取令牌,然后将数据发布到登录。

在WPF中我有这个课程:

// CookieAwareWebClient.cs
public class CookieAwareWebClient : WebClient
{
    public string Method;
    public CookieContainer CookieContainer { get; set; }

    public CookieAwareWebClient()
        : this(new CookieContainer())
    {
    }

    public CookieAwareWebClient(CookieContainer cookies)
    {
        this.CookieContainer = cookies;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
            (request as HttpWebRequest).ServicePoint.Expect100Continue = false;
            (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
            (request as HttpWebRequest).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            (request as HttpWebRequest).KeepAlive = true;
            (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.Deflate |
                                                                 DecompressionMethods.GZip;
            if (Method == "POST")
            {
                (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";
            }

        }
        HttpWebRequest httpRequest = (HttpWebRequest)request;
        httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        return httpRequest;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

        if (setCookieHeader != null)
        {
            try
            {
                if (setCookieHeader != null)
                {
                    Cookie cookie = new Cookie(); //create cookie
                    this.CookieContainer.Add(cookie);
                }
            }
            catch (Exception)
            {
            }
        }
        return response;
    }
}

,就像这样使用:

// Program.cs
// ...
CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);
string response = client.DownloadString("LINK TO WEBSITE TO GET COOKIES");

// Get the csrf token from response html
var tokenValue = Regex.Match(response, "name='csrf_token' 
value='(.+?)'").Groups[1].Value;

// Prepare values to send
string token = $"csrf_token={tokenValue}&";
string email = $"email={email}&";
string password = $"password={password}&";
string rememberme = $"rememberme=on&";
string submit = $"submit=Login";

string postData = token + email + password + rememberme + submit;

client.Method = "POST";
response = client.UploadString("LINK TO LOGIN ACTION", postData);

这在WPF中完美无瑕。如何在UWP中实现这样的效果? 我尝试使用HttpClient,但是我得到了错误的响应,javascript没有加载,或者我无法读取响应。

到目前为止,我试图连接到普通网站并阅读html,以获取令牌。但是我得到了回复错误。

var handler = new HttpClientHandler { AllowAutoRedirect = true };
var client = new HttpClient(handler);

client.DefaultRequestHeaders.TryAddWithoutValidation("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
client.DefaultRequestHeaders.TryAddWithoutValidation("KeepAlive", "true");
client.DefaultRequestHeaders.TryAddWithoutValidation("ServicePoint.Expect100Continue", "false");


var response = await client.GetAsync(new Uri("LINK"));

// ERROR => System.Net.Http.HttpRequestException: "Response status code does not indicate success: 503 ()."
response.EnsureSuccessStatusCode();
var html = await response.Content.ReadAsStringAsync();

1 个答案:

答案 0 :(得分:1)

您需要向处理程序添加CookieContainer,以便能够访问请求中的Cookie返回

//have a cookie container before making the request
var cookies = new CookieContainer();
var handler = new HttpClientHandler() {
    AllowAutoRedirect = true,
    CookieContainer = cookies,
    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
};

//Handle TLS protocols (https)
System.Net.ServicePointManager.SecurityProtocol =
    System.Net.SecurityProtocolType.Tls
    | System.Net.SecurityProtocolType.Tls11
    | System.Net.SecurityProtocolType.Tls12;

var client = new HttpClient(handler);

client.DefaultRequestHeaders.TryAddWithoutValidation("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
client.DefaultRequestHeaders.TryAddWithoutValidation("KeepAlive", "true");
client.DefaultRequestHeaders.TryAddWithoutValidation("ServicePoint.Expect100Continue", "false");

var uri = new Uri("Link");
var response = await client.GetAsync(uri);

var html = await response.Content.ReadAsStringAsync();

// Get the csrf token from response html
var tokenValue = Regex.Match(html, "name='csrf_token' value='(.+?)'").Groups[1].Value;


//...Prepare values to send
相关问题