Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用cookies的UWP登录网站_C#_Wpf_Uwp_Httpclient_Webclient - Fatal编程技术网

C# 使用cookies的UWP登录网站

C# 使用cookies的UWP登录网站,c#,wpf,uwp,httpclient,webclient,C#,Wpf,Uwp,Httpclient,Webclient,我正在尝试将WPF应用程序转换为UWP,但正在绞尽脑汁研究如何使该功能正常工作 WPF应用程序连接到一个网站,获取cookie,从html读取令牌,然后将数据发布到登录 在WPF中,我上过这样的课: // CookieAwareWebClient.cs public class CookieAwareWebClient : WebClient { public string Method; public CookieContainer CookieContainer { get;

我正在尝试将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();
您需要将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

显示您在HttpClient上尝试了什么,如果有错误,以及在我从html代码中提取csrf时所需的行为。我无法获取html代码,因为如果我执行字符串html=client.GetStringAsyncuri;我得到一个错误,如果不是503代码,响应将被删除。@er4zox我不理解您的评论。您可以从响应的内容中获取html。@er4zox 503还表明问题出在您正在调用的服务器上,而不是您的客户端。那么我做错了什么。当我使用wpf代码时,它工作得非常好。当我阅读html时,我只得到cloudflare页面,而不是真正的页面。@er4zox链接被称为http还是https?