从Xamarin.forms中的httprequest检索cookie



帮助我,我无法从httprequest那里得到cookie,我尝试了插件。设置,我也尝试了pcl共享,在这个问题上待一个月

        public async Task<bool> PostAsync(AuthUser user)
    {
        var CookieContainer = new CookieContainer();
        var handler = new HttpClientHandler() { CookieContainer = 
        CookieContainer };
        var _client = new HttpClient(handler);
        IEnumerable<string> cookieStrings = null;
        //var httpClient = new HttpClient();
        _client.DefaultRequestHeaders.Accept.Add(new 
         MediaTypeWithQualityHeaderValue("application/json"));
        var json = JsonConvert.SerializeObject(user);
            HttpContent httpContent = new StringContent(json);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                string url = WebServiceUrl + "j_spring_security_check?j_username=" + user.j_username +"&j_password=" + user.j_password + "&ajax=true";
            HttpResponseMessage result = await _client.PostAsync(url, httpContent);
                IEnumerable<string> cookies;
                if (result.Headers.TryGetValues("set-cookie", out cookies))
                {
                    foreach (var c in cookies)
                    {
                    await App.Current.MainPage.DisplayAlert("Cookie", c , "OK");
                    }
                }
                if (result.IsSuccessStatusCode)
                {
                    using (var responsecontent = result.Content)
                    {
                    string resultString = responsecontent.ReadAsStringAsync().Result;
                        var response = JsonConvert.DeserializeObject<AuthUser>(resultString);
                        if (response.error != null)
                        {
                            await App.Current.MainPage.DisplayAlert("Error", response.result.error, "OK");
                            return false;
                        }
                        else if (response.result.success.Equals("1"))
                        {
                        App.Current.MainPage = new NavigationPage(new TimelineMenuPage(response.result.user_id.ToString(), response.result.token));
                        return true;
                        }
                    }
                }
                return result.IsSuccessStatusCode;
        }
            catch (Exception e)
            {
               await App.Current.MainPage.DisplayAlert("Alert", e.ToString(), "OK");
              throw;
            }
        }

调试时跳过此部分:

if (result.Headers.TryGetValues("set-cookie", out cookies))
{
foreach (var c in cookies)
{
await App.Current.MainPage.DisplayAlert("Cookie", c , "OK");
}
}

**,然后我进入cookiecontainer count = 0 **

由于您已经在使用CookieContainer,并且您会知道您从中获得的URI,为什么不直接从容器中获得cookie,而不是设置 - cookie命令,然后您必须解析。

cookieContainer.GetCookies(new Uri("mydomain.com"));

在您的httprequest之后,它会自动将它们放入烹饪剂中。

相关内容

  • 没有找到相关文章

最新更新