UWP WebRequest替换HttpClient Cookie?

时间:2016-03-27 05:07:34

标签: cookies win-universal-app

因为我要么倾向于找到正确的答案,要么根本就不在那里...... hek我如何取代过时的" WebRequest正确使用HttpClient"替换"?

在WebRequest中,我要求序列化&分析实际的cookie,因为网页返回一个部分JSON cookie ...但是...我仍然没有找到一种方法从frking HttpClient获得一个合适的CookieContainer(或任何形式的cookie)...也...每一个谷歌请求引导我20000000岁的答案或过时的文件(+一些upToDate文档,所有只是参考" GET"请求没有涉及任何cookie -.- *)

如果有人能引导我走上正确的道路,那将是友善的...... THX

招呼 X39

Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
client.DefaultRequestHeaders.UserAgent.TryParseAdd(app.Settings.UserAgent);
var response = await client.PostAsync(new Uri(app.Settings.Pr0grammUrl.Api + "user/login"), new Windows.Web.Http.HttpStringContent(postDataBuilder.ToString()));

1 个答案:

答案 0 :(得分:1)

默认情况下,HttpClient通过默认HttpBaseProtocolFilter自行处理Cookie。您可以通过GetCookies类的HttpCookieManager方法获取与URI相关联的Cookie:

  

获取包含HttpCookie实例的HttpCookieCollection   与特定URI相关联的。

using (var protocolFilter = new HttpBaseProtocolFilter()) {
    var cookieManager = protocolFilter.CookieManager;
    var cookies = cookieManager.GetCookies(uri);
    foreach (var cookie in cookies) {
       // Here is each cookie
    }
}

您还应该能够通过HTTP请求和响应标头设置/获取cookie。要禁止HttpClient自行处理cookie,请创建HttpBaseProtocolFilter的实例并将CookieUsageBehavior设置为HttpCookieUsageBehavior.NoCookies:

  

NoCookies:不要自动处理cookie。

// Create http filter
httpFilter = new HttpBaseProtocolFilter();
httpFilter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;

// Create http client
httpClient = new HttpClient(httpFilter);

// Handle cookies through HTTP headers