【问题标题】:HttpClient is sending extra cookiesHttpClient 正在发送额外的 cookie
【发布时间】:2016-02-24 07:00:51
【问题描述】:

运行 UWP 应用*

所以我有一个 HttpClient 及其关联的处理程序。我正在向网站发出请求,传入指定的标头,并使用指定的 CookieContainer,该 CookieContainer 在请求开始时为空。

当我发送请求时,Fiddler 显示正在发送的额外 cookie 我没有添加。他们来自哪里?

CookieContainer cookieJar = new CookieContainer();                
HttpClientHandler handler = new HttpClientHandler( );
handler.UseDefaultCredentials = false;
handler.CookieContainer = cookieJar;
handler.Proxy = null;
using (var client = new HttpClient(handler as HttpClientHandler))
{
    HttpResponseMessage response = new HttpResponseMessage();
    String loginUrl = Const.BUNGIE_LOGIN_URI + (provider == Const.XBOX_PLATFORM ? Const.XBOX_LOGIN : Const.PS_LOGIN);
    client.BaseAddress = new Uri(loginUrl);
    //client.Timeout = new TimeSpan(0, 0, 0, 0, 450);
    client.DefaultRequestHeaders.Add("Referer", "http://www.bungie.net");
    client.DefaultRequestHeaders.Add("User-Agent", Const.USERAGENT);
    client.DefaultRequestHeaders.Add("X-API-Key", Const.X_API_KEY);
    client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
    handler.AutomaticDecompression = DecompressionMethods.GZip;

    response = client.GetAsync("").Result;
    response.ReadCookies(); //adds cookies to cookieJar
 }

What fiddler shows

现在,由于在发出请求之前关联的 CookieContainer 是空的,这些 cookie 是从哪里来的?它们可以访问吗?如果我想要它们的值,我将如何获得它们?

编辑:它们是从哪里添加到我的 HttpClient 请求中的? HttpClient 有通用的 CookieContainer/缓存吗?我有两个单独的 HttpClient 实例,当客户端(A)发出请求时,它收到了一个“set-cookie”标头,设置了一个“bungled”cookie。

稍后,HttpClient 的一个单独实例 Client (B) 向同一个网站发出请求,发送 Client (A) 中设置的 cookie。

我没有明确地将这个 cookie 附加到客户端 (B) 的请求中,那么它是如何添加的?

【问题讨论】:

  • 什么是cookieJar,它是如何创建的?
  • 另外,由于您明确将代理设置为 null,您如何使用 Fiddler 捕获数据?
  • 它是一个 CookieContainer。更新代码以反映
  • @DavidG 我应该不能吗?如果该行存在与否,我可以看到请求。
  • 发送的 Cookie 是服务器端功能。当你问这些 cookie 是什么时,应该通过将 Fiddler 或 wireshark 运行到相同的端点来看到答案,这将证明它是服务器端的事情。这意味着答案与页面中呈现的内容有关。例如,可能有对 Google Analytics 或其他设置“额外”cookies 的第三方事物的引用。

标签: c# cookies httpclient fiddler uwp


【解决方案1】:

在 Windows 10 build 10240 上,System.Net.Http.HttpClient 是 Windows.Web.Http.HttpClient (more info here) 之上的包装器,因此,cookie 现在的工作方式略有不同。

要删除这些额外的 cookie,您需要使用 HttpCookieManager 删除 cookie:

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = filter.CookieManager;
foreach (HttpCookie cookie in cookieManager.GetCookies(uri))
{
    cookieManager.DeleteCookie();
}

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多