How can I get HttpOnly cookies in Windows Phone 8?

后端 未结 2 652
轻奢々
轻奢々 2020-12-11 21:47

I am working in a Windows Phone 8 PCL project. I am using a 3rd party REST API and I need to use a few HttpOnly cookies originated by the API. It seems like getting/access

相关标签:
2条回答
  • 2020-12-11 21:53

    The HttpOnly cookie is inside the CookieContainer, it's only that is not exposed. If you set the same instance of that CookieContainer to the next request it will set the hidden cookie there (as long as the request is made to the same site the cookie specifies).

    That solution will work until you need to serialize and deserialize the CookieContainer because you are restoring state. Once you do that you lose the HttpOnly cookies hidden inside the CookieContainer. So, a more permanent solution would be using Sockets directly for that request, read the raw request as a string, extract the cookie and set it to the next requests. Here's the code for using Sockets in 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;
    }
    
    0 讨论(0)
  • 2020-12-11 21:56

    There is also a second possibility - to manually go through response headers, grab and then parse Set-Cookie headers using a bunch of custom code.

    It looks something like that, when you are going to match and save a single PHPSESSID cookie (assume LatestResponse is your HttpResponseMessage containing website response):

    if (LatestResponse.Headers.ToString().IndexOf("Set-Cookie:") != -1) try
            {
                string sid = LatestResponse.Headers.ToString();
                sid = sid.Substring(sid.IndexOf("Set-Cookie:"), 128);
                    if (sid.IndexOf("PHPSESSID=") != -1)
                    {
                        settings.Values["SessionID"] = SessionID = sid.Substring(sid.IndexOf("PHPSESSID=") + 10, sid.IndexOf(';') - sid.IndexOf("PHPSESSID=") - 10);
                        handler.CookieContainer.Add(new Uri("http://example.com", UriKind.Absolute), new System.Net.Cookie("PHPSESSID", SessionID));
                    }
            } catch (Exception e) { 
                // your exception handling
            }
    

    Note this code inserts the cookie to CookieContainer for that object's life unless manually deleted. If you want to include it in a new object, just pull the right setting value and add it to your new container.

    0 讨论(0)
提交回复
热议问题