我在 Windows Phone 8 PCL 项目中工作。我正在使用 3rd 方 REST API,我需要使用一些由 API 发起的 HttpOnly cookie。除非您使用反射或其他一些后门,否则似乎无法从 HttpClientHandler 的 CookieContainer 获取/访问 HttpOnly cookie。

我需要获取这些 cookie 并在后续请求中发送它们,否则我将无法使用此 API - 我该如何完成?这是我当前的请求代码的样子:

提前致谢。

//Some request
HttpRequestMessage request = new HttpRequestMessage();
HttpClientHandler handler = new HttpClientHandler();

//Cycle through the cookie store and add existing cookies for the susbsequent request
foreach (KeyValuePair<string, Cookie> cookie in CookieManager.Instance.Cookies)
{
            handler.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value));
}

//Send the request asynchronously
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();

//Parse all returned cookies and place in cookie store
foreach (Cookie clientcookie in handler.CookieContainer.GetCookies(request.RequestUri))
{
     if (!CookieManager.Instance.Cookies.ContainsKey(clientcookie.Name))
                CookieManager.Instance.Cookies.Add(clientcookie.Name, clientcookie);
            else
                CookieManager.Instance.Cookies[clientcookie.Name] = clientcookie;
}

HttpClient httpClient = new HttpClient(handler);

最佳答案

HttpOnly cookie 位于 CookieContainer 内,只是未公开。如果您将该 CookieContainer 的相同实例设置为下一个请求,它将在那里设置隐藏的 cookie(只要请求是向 cookie 指定的同一站点发出的)。

该解决方案将一直有效,直到您需要序列化和反序列化 CookieContainer,因为您正在恢复状态。一旦你这样做了,你就会丢失隐藏在 CookieContainer 中的 HttpOnly cookie。因此,更持久的解决方案是直接针对该请求使用 Sockets,将原始请求作为字符串读取,提取 cookie 并将其设置为下一个请求。下面是在 Windows Phone 8 中使用套接字的代码:

public async Task<string> Send(Uri requestUri, string request)
{
   var socket = new StreamSocket();
   var hostname = new HostName(requestUri.Host);
   await socket.ConnectAsync(hostname, requestUri.Port.ToString());

   var writer = new DataWriter(socket.OutputStream);
   writer.WriteString(request);
   await writer.StoreAsync();

   var reader = new DataReader(socket.InputStream)
   {
      InputStreamOptions = InputStreamOptions.Partial
   };
   var count = await reader.LoadAsync(512);

    if (count > 0)
      return reader.ReadString(count);
    return null;
}

关于cookies - 如何在 Windows Phone 8 中获取 HttpOnly cookie?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16290773/

10-09 07:29