【问题标题】:Cookies not working using WebClient on Windows PhoneCookie 无法在 Windows Phone 上使用 WebClient
【发布时间】:2014-04-29 01:03:42
【问题描述】:

我的问题是,当我使用新的 webclient 向 WebService 发送 url 时,它要求我登录,在搜索了这个问题后,我发现你需要保存 cookie,但它对我不起作用。

根据您的要求,这是完整代码

namespace PhoneApp8
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        public class OuterRootObject
        {
            public string d { get; set; }
        }

        public class Globals
        {
            public bool MultiSessionsAllowed { get; set; }
            public int CommCalcType { get; set; }
            public int PriceChangedTimer { get; set; }
            public int ValidLotsLocation { get; set; }
            public bool CustumizeTradeMsg { get; set; }
            public object FirstWhiteLabeledOffice { get; set; }
            public int DealerTreePriv { get; set; }
            public int ClientConnectTimer { get; set; }
            public int ClientTimeoutTimer { get; set; }
            public double DefaultLots { get; set; }
            public string WebSecurityID { get; set; }
            public int ServerGMT { get; set; }
        }

        public class VersionInfo
        {
            public int Rel { get; set; }
            public int Ver { get; set; }
            public int Patch { get; set; }
            public int ForceUpdate { get; set; }
            public int UpdateType { get; set; }
            public Globals Globals { get; set; }
        }

        public class SystemLockInfo
        {
            public int MinutesRemaining { get; set; }
            public int HoursRemaining { get; set; }
            public int DaysRemaining { get; set; }
            public int Maintanance { get; set; }
            public int WillBeLocked { get; set; }
        }

        public class RootObject
        {
            public string sessionid { get; set; }
            public VersionInfo VersionInfo { get; set; }
            public SystemLockInfo SystemLockInfo { get; set; }
            public string FirstWhiteLabel { get; set; }
            public string WLID { get; set; }
            public bool CheckWhiteLabel { get; set; }
            public string Password { get; set; }
            public string Username { get; set; }
            public DateTime LastTickTime { get; set; }
            public int SelectedAccount { get; set; }
            public int Name { get; set; }
            public object ServicePath { get; set; }
            public string GWSessionID { get; set; }
            public string IP { get; set; }
            public string SessionDateStart { get; set; }
            public string CompanyName { get; set; }
            public string UserId { get; set; }
            public string DemoClient { get; set; }
            public string FName { get; set; }
            public string SName { get; set; }
            public string TName { get; set; }
            public string LName { get; set; }
            public object Sms { get; set; }
            public string isReadOnly { get; set; }
            public string SchSms { get; set; }
            public string AlertSms { get; set; }
            public object Temp { get; set; }
            public string GMTOffset { get; set; }
            public string SvrGMT { get; set; }
            public object ClientType { get; set; }
            public string EnableNews { get; set; }
            public string PublicSlideNews { get; set; }
            public string PrivateSlideNews { get; set; }
            public int DealerTreePriv { get; set; }
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string baseuri = "http://IP in the comment/vertexweb10/webservice.svc/login?username=%22user15650%22&password=%22898k%22";
            CookieAwareWebClient wc = new CookieAwareWebClient();
            wc.DownloadStringCompleted += ParseProducts_AsJson;
            Uri uri = new Uri(baseuri);
            wc.DownloadStringAsync(uri);
        }

        private void ParseProducts_AsJson(object sender, DownloadStringCompletedEventArgs e)
        {
            string raw = e.Result;
            string webResponse = e.Result;

            MessageBox.Show(webResponse as string);
            var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>(webResponse);
            var root = JsonConvert.DeserializeObject<RootObject>(outerRoot.d);

            MessageBox.Show("hello " + root.Username + "    " + root.UserId + "    " + root.sessionid);
            var UserIdVal= Convert.ToInt16 (root.UserId);

            if (UserIdVal == -1 || UserIdVal == -207)
                MessageBox.Show("Invalid username or password");
            else if (UserIdVal == -231)
            {
                MessageBox.Show("You must have at least one account");
            }

            else if (webResponse == null || webResponse == "" || UserIdVal < 0)
            {
                MessageBox.Show("Error while login.Please try later");
            }

            else if (UserIdVal > 0)
            {

                string baseuri1 = "http://IP in the comment/vertexweb10/webservice.svc/getallsymbols?AccountID=1122336675";
                CookieAwareWebClient wc1 = new CookieAwareWebClient();
                wc1.DownloadStringCompleted += ParseProducts_AsJson1;
                Uri uri1 = new Uri(baseuri1);
                wc1.DownloadStringAsync(uri1);
                MessageBox.Show("You have loged in");
                NavigationService.Navigate(new Uri("/page2.xaml", UriKind.Relative));
            }

            else
            {
                MessageBox.Show("Invalid username or password");
            } 


        }

        private void ParseProducts_AsJson1(object sender, DownloadStringCompletedEventArgs e)
        {
            string raw1 = e.Result;
            string webResponse1 = e.Result;
            MessageBox.Show(webResponse1 as string);
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        class CookieAwareWebClient : WebClient
        {
            [System.Security.SecuritySafeCritical]
            private CookieContainer cookie;

            public CookieContainer Cookie { get { return cookie; } }

            public CookieAwareWebClient()
            {
                cookie = new CookieContainer();
            }

            public CookieAwareWebClient(CookieContainer givenContainer)
            {
                cookie = givenContainer;
            }
        }
    }
}

我认为错误出在 cookie 容器中,这是我使用的最后一个 cookieaware(我已经尝试了 10 多个 cookie 容器代码)

【问题讨论】:

  • 任何帮助,我需要解决它:(
  • 我在这里发布了完整的代码,ip 是 74.54.46.178,请帮我做这个
  • 请帮帮我,我的问题没有解决办法。

标签: c# windows-phone-7 cookies windows-phone-8


【解决方案1】:

这是代码,它的作用是调用第一个 Url 并获得响应,如果响应良好,它将 cookie 复制到 sessionCookie 变量。并在第二次调用中使用它

在同一页面的某个位置声明 sessioncookie

public static CookieContainer sessionCookie;

然后将其复制到您的按钮单击中

  public static async Task<string> SendRequestGetResponse()
    {
        try
        {
                   var postRequest = (HttpWebRequest)WebRequest.Create("http://74.54.46.178/vertexweb10/webservice.svc/login?username=%22user15650%22&password=%22898k%22");

            postRequest.Method = "GET";
            if (sessionCookie == null)
            {
                postRequest.CookieContainer = new CookieContainer();
            }
            else
            {
                postRequest.CookieContainer = sessionCookie;
            }

            HttpWebResponse postResponse = (HttpWebResponse)await postRequest.GetResponseAsync();

            if (postResponse != null)
            {
                var postResponseStream = postResponse.GetResponseStream();
                var postStreamReader = new StreamReader(postResponseStream);

                string response = await postStreamReader.ReadToEndAsync();

                if (sessionCookie == null)
                {
                    sessionCookie = postRequest.CookieContainer;
                }
            }

        var postRequest1 = (HttpWebRequest)WebRequest.Create("http://74.54.46.178/vertexweb10/webservice.svc/getallsymbols?AccountID=1122336675");              
            postRequest1.Method = "GET";
            if (sessionCookie == null)
            {
                postRequest1.CookieContainer = new CookieContainer();
            }
            else
            {
                postRequest1.CookieContainer = sessionCookie;
            }

            HttpWebResponse postResponse1 = (HttpWebResponse)await postRequest1.GetResponseAsync();

            if (postResponse1 != null)
            {
                var postResponseStream1 = postResponse1.GetResponseStream();
                var postStreamReader1 = new StreamReader(postResponseStream1);

                string response1 = await postStreamReader1.ReadToEndAsync();

            }
     }
  }

【讨论】:

  • 它不起作用,我不知道是什么问题,我认为是因为收到的cookie是httpOnly,请指教
  • 您能否分享您为登录请求和其他请求设置标头(如内容类型、请求类型等)的代码。我已经编辑了我的答案,并包含了我为请求设置标头的部分。
  • 亲爱的 Jagath,这是我使用的完整代码,IP 是 74.54.46.178,我知道它的代码不好,因为我是编程新手,请帮助我这样做
  • 我已经用我的代码编辑了我的答案,因为我得到了成功的回报。
  • 对不起,亲爱的,它不能使用我的代码,你能帮我处理我的代码吗?我的意思是使用类 CookieAwareWebClient : WebClient
【解决方案2】:

我已经使用

解决了我的问题
request.CookieContainer = cookieJar;

然后我在第二个请求中使用相同的 cookieJar

var request = HttpWebRequest.Create(new Uri("http://x.x.x.x/vertexweb10/webservice.svc/getallsymbols?AccountID=1122336675")) as HttpWebRequest;
request.Method = "GET";
request.CookieContainer = cookieJar;
request.BeginGetResponse(ar =>
{
    HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
    using (var response = (HttpWebResponse)req2.EndGetResponse(ar))
    {
        using (Stream stream = response.GetResponseStream())
        {
            using (var reader = new StreamReader(stream))
            {




                //the code you need


            }
        }

    }

}, request);

【讨论】:

    猜你喜欢
    • 2012-03-15
    • 2013-05-14
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多