加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

如何在Windows Phone 8中获取HttpOnly cookie?

发布时间:2020-12-14 03:51:41 所属栏目:Windows 来源:网络整理
导读:我在 Windows Phone 8 PCL项目中工作.我正在使用第三方REST API,我需要使用由API发起的一些HttpOnly cookie.似乎从HttpClientHandler的CookieContainer获取/访问HttpOnly cookie似乎是不可能的,除非你使用反射或其他一些后门. 我需要获取这些cookie并在后续
我在 Windows Phone 8 PCL项目中工作.我正在使用第三方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.因此,更永久的解决方案是直接为该请求使用套接字,将原始请求作为字符串读取,提取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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读