当前位置: 首页>>代码示例>>C#>>正文


C# RestRequest.AddCookie方法代码示例

本文整理汇总了C#中RestSharp.RestRequest.AddCookie方法的典型用法代码示例。如果您正苦于以下问题:C# RestRequest.AddCookie方法的具体用法?C# RestRequest.AddCookie怎么用?C# RestRequest.AddCookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在RestSharp.RestRequest的用法示例。


在下文中一共展示了RestRequest.AddCookie方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DownloadAllFilesLocal

        static void DownloadAllFilesLocal(Dictionary<string, string> downloadList, string chosenFilePath, string chosenFolderName, IRestResponse loginResponse)
        {
            string filePath;
            Console.WriteLine("");
            //Regex setup for removing multiple spaces
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(@"[ ]{2,}", options);

            if (chosenFolderName == string.Empty)
            {
                filePath = string.Concat(chosenFilePath, "");
            }
            else
            {
                Directory.CreateDirectory(string.Concat(chosenFilePath, "\\", chosenFolderName));
                filePath = string.Concat(chosenFilePath, "\\", chosenFolderName, "\\");
            }
            foreach (KeyValuePair<string, string> keyValuePair in downloadList)
            {
                string tempFilePath = filePath;
                RestClient client = new RestClient(keyValuePair.Value);
                RestRequest request = new RestRequest(Method.GET);
                request.AddCookie(loginResponse.Cookies[0].Name, loginResponse.Cookies[0].Value);
                Uri uri = client.Execute(request).ResponseUri;
                tempFilePath = string.Concat(tempFilePath, uri.Segments.Last<string>());
                WebClient webClient = new WebClient();
                webClient.Headers.Add(HttpRequestHeader.Cookie, string.Concat(loginResponse.Cookies[0].Name, "=", loginResponse.Cookies[0].Value));
                webClient.DownloadFile(uri, regex.Replace(HttpUtility.HtmlDecode(HttpUtility.UrlDecode(tempFilePath)),@" "));
                Program.ConsoleSetColor(ConsoleColor.Gray);
                Console.WriteLine(HttpUtility.UrlDecode(string.Concat(uri.Segments.Last<string>(), " complete")));
            }
        }
开发者ID:nishanthkarthik,项目名称:moodlesharp-cli,代码行数:32,代码来源:Program.cs

示例2: Search

        public IRestResponse<MarketplaceSearchResponse> Search(string query = "", int start = 0, int count = 10)
        {
            var client = new MarketplaceClient(BaseUrl);

            var request = new RestRequest("/", Method.GET);
            request.AddHeader("Accept", "*/*");
            request.AddHeader("Accept-Enclding", "gzip,deflat,sdch");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("HOST", "steamcommunity.com");

            request.AddCookie("__ngDebug", "false");
            request.AddCookie("Steam_Language", "english");
            request.AddCookie("sessionid", "MTE3OTk1OTgyNQ");
            request.AddCookie("steamCC_67_167_177_70", "US");
            request.AddCookie("__utma", "268881843.805413192.1378770011.1382167972.1382171160.10");
            request.AddCookie("__utmb", "268881843.1.10.1382171160");
            request.AddCookie("__utmc", "268881843");
            request.AddCookie("__utmz", "268881843.1382171160.10.6.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)");
            //request.AddCookie("timezoneOffset", "-14400,0");

            //request.Timeout = 5*1000;
            request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");

            request.AddParameter("query", query, ParameterType.GetOrPost);
            request.AddParameter("start", start, ParameterType.GetOrPost);
            request.AddParameter("count", count, ParameterType.GetOrPost);

            var response = client.Get<MarketplaceSearchResponse>(request);

            return response;
        }
开发者ID:Zodge,项目名称:GetSteamed,代码行数:31,代码来源:MarketplaceRequest.cs

示例3: SetAuthenticationCookies

 private void SetAuthenticationCookies(RestRequest restRequest, IEnumerable<KeyValuePair<string, string>> authenticationCookies)
 {
     foreach (KeyValuePair<string, string> cookie in authenticationCookies)
     {
         restRequest.AddCookie(cookie.Key, cookie.Value);
     }
 }
开发者ID:DefiSolutions,项目名称:YouTrack.Rest,代码行数:7,代码来源:RestRequestFactory.cs

示例4: GetIssues

        private static string GetIssues(RestResponseCookie cookie, RestClient client)
        {
            var request = new RestRequest("rest/issue/byproject/TP?max=1000", Method.GET);
            request.AddCookie(cookie.Name, cookie.Value);
            var response = client.Execute(request);

            ThrowIfNotOk(response, "could not get issues");

            return response.Content;
        }
开发者ID:ursenzler,项目名称:TechnikPortfolio,代码行数:10,代码来源:YouTrack.cs

示例5: SetAuthentication

 protected void SetAuthentication(RestRequest request, AuthMethod authMethod, string sessionId)
 {
     if (String.IsNullOrEmpty(sessionId)) // Check if we have a valid id
     {
         return;
     }
     if (authMethod == AuthMethod.SessionId)
     {
         request.AddParameter(SessionIdParameterName, sessionId);
     }
     else // Cookie
     {
         request.AddCookie(SessionIdCookieName, sessionId);
     }
 }
开发者ID:sburnicki,项目名称:ODSCmdlets,代码行数:15,代码来源:DataspaceRequest.cs

示例6: SetUp

        public void SetUp()
        {
            _client = new RestClient(baseUrl);

              var requestToGetTheAntiForgeryToken = new RestRequest("NewGame");
              requestToGetTheAntiForgeryToken.Method = Method.GET;
              var result = _client.Execute(requestToGetTheAntiForgeryToken);
              var antiForgeryCookie = result.Cookies[0];
              var match = Regex.Match(result.Content,
            "<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"(?<token>.*?)\" />"); //this feels brittle, but it works today, 2013-09-21
              var token = match.Groups["token"].Value;

              _request = new RestRequest("NewGame");
              _request.Method = Method.POST;
              _request.AddCookie(antiForgeryCookie.Name, antiForgeryCookie.Value);
              _request.AddParameter("__RequestVerificationToken", token);
        }
开发者ID:pseale,项目名称:monopoly-dotnet,代码行数:17,代码来源:SubmittingTheStartNewGameForm.cs

示例7: GetCompanies

        public List<Company> GetCompanies()
        {
            List<Company> companyList = new List<Company> ();
            RestClient client = new RestClient (@"http://internship.iitm.ac.in/students/comp_list.php");
            RestRequest request = new RestRequest (Method.GET);
            request.AddCookie (cookie.Name, cookie.Value);
            IRestResponse response = client.Execute (request);
            if (response.StatusCode != HttpStatusCode.OK)
                return new List<Company> ();
            string cleanHtml = CleanHtml (response.Content);

            //Parse table into Company objects
            HtmlDocument htmlDoc = new HtmlDocument ();
            htmlDoc.LoadHtml (cleanHtml);
            HtmlNode companyTable = htmlDoc.DocumentNode.SelectNodes ("//table") [3];

            ConArt.Out ("Starting data collection...");
            //Select rows and parse data within
            HtmlNodeCollection rowsList = companyTable.SelectNodes ("tr");
            for (int i = 1; i < rowsList.Count; ++i)
            {
                HtmlNodeCollection columnList = rowsList [i].SelectNodes ("td");
                Company company = new Company ();
                company.Name = columnList [1].InnerText.Replace ("\n", "");
                company.Profile = columnList [2].InnerText;
                string profileAddress = columnList [2].SelectSingleNode ("a").GetAttributeValue ("href", "");
                company.DetailUri = new Uri ("http://internship.iitm.ac.in/students/" + HttpUtility.HtmlDecode (profileAddress), UriKind.Absolute);
                DateTime.TryParse (columnList [3].InnerText, out company.TalkDate);
                DateTime.TryParse (columnList [4].InnerText, out company.ResumeDeadline);
                DateTime.TryParse (columnList [5].InnerText, out company.TestDate);
                DateTime.TryParse (columnList [6].InnerText, out company.GdDate);
                DateTime.TryParse (columnList [7].InnerText, out company.TalkDate);
                company.Status = Parsers.ParseStatus (columnList [7].InnerText);
                company.DetailSnippet = GetCompanyDetails (company);
                companyList.Add (company);

                //Update progress bar
                Console.CursorLeft = 0;
                Console.Write ( (int)i * 100 / rowsList.Count + "% Complete" );
            }
            Console.CursorLeft = 0;
            Console.WriteLine("                 ");

            return companyList;
        }
开发者ID:nishanthkarthik,项目名称:internship-mono,代码行数:45,代码来源:LibIntern.cs

示例8: GetDownloadUrl

 static Dictionary<string, string> GetDownloadUrl(IRestResponse loginResponse, Dictionary<string, string> courseDictionary, int courseKeyValuePairIndex)
 {
     Dictionary<string, string> urlList = new Dictionary<string, string>();
     KeyValuePair<string, string> keyValuePair = courseDictionary.ElementAt<KeyValuePair<string, string>>(courseKeyValuePairIndex);
     RestClient client = new RestClient(keyValuePair.Value);
     RestRequest request = new RestRequest(Method.GET);
     request.AddCookie(loginResponse.Cookies[0].Name, loginResponse.Cookies[0].Value);
     IRestResponse response = client.Execute(request);
     HtmlDocument document = new HtmlDocument();
     document.Load(Utils.GenerateStreamFromString(response.Content));
     foreach (HtmlNode htmlNode in (IEnumerable<HtmlNode>)document.DocumentNode.SelectNodes("//*[@class=\"activityinstance\"]"))
     {
         if (urlList.ContainsKey(htmlNode.InnerText))
         {
             continue;
         }
         urlList.Add(htmlNode.InnerText, htmlNode.ChildNodes[0].GetAttributeValue("href", ""));
     }
     return urlList;
 }
开发者ID:nishanthkarthik,项目名称:moodlesharp-cli,代码行数:20,代码来源:Program.cs

示例9: CreateCt

 public IRestResponse<Upid> CreateCt(LxcTemplate template)
 {
     var client = new RestClient (_baseUrl);
     var request = new RestRequest($"nodes/{_node}/lxc", Method.POST) {RequestFormat = DataFormat.Json};
     request.AddHeader ("CSRFPreventionToken", _apiTicket.CSRFPreventionToken);
     request.AddCookie ("PVEAuthCookie", _apiTicket.ticket);
     //request.RootElement = "data";
     request.AddParameter ("ostemplate", template.Ostemplate);
     request.AddParameter ("vmid", template.Vmid);
     request.AddParameter ("storage", template.Storage);
     request.AddParameter ("password", template.Password);
     request.AddParameter ("hostname", template.Hostname);
     request.AddParameter ("memory", template.Memory);
     request.AddParameter ("swap", template.Swap);
     request.AddParameter ("cpuunits", template.Cpuunits);
     request.AddParameter ("net0", template.Net);
     request.AddParameter ("ostype", template.Ostype);
     request.AddParameter ("pool", template.Pool);
     var response = client.Execute<Upid>(request);
     return response;
 }
开发者ID:ionelanton,项目名称:ProxmoxSharp,代码行数:21,代码来源:ApiClient.cs

示例10: UpLoadAttendanceResults

        void UpLoadAttendanceResults()
        {
            string cookieName = string.Empty;
            string cookieValue = string.Empty;
            var user = Common.GetCurrentUser ();

            var login = new RestClient(Settings.URLs.Host);

            //login.Authenticator = new SimpleAuthenticator("identifier", "[email protected]", "password", "q1234567");
            login.Authenticator = new SimpleAuthenticator(@"identifier", user.username, @"password", user.password);
            login.CookieContainer = new CookieContainer();

            var request = new RestRequest(@"auth/local", Method.POST);
            var response = login.Execute<User>(request);
            User userRes = response.Data;

            if (userRes == null)
            {
                RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось пройти аутентификацию!"));
            }

            cookieName = response.Cookies[0].Name;
            cookieValue = response.Cookies[0].Value;

            var queueToUpload = (List<SyncQueue>) SyncQueueManager.GetSyncQueue(selectedDate);
            foreach (var q in queueToUpload) {
                try {
                    if (( q.type == SyncQueueType.sqtAttendanceResult) && (!q.isSync)) {
                        var client = new RestClient(Settings.URLs.Host);

                        //Debug.WriteLine(@"Получение информации о себе.", @"Info");
                        AttendanceResult attendanceResult = SyncQueueManager.GetAttendaceResult(q.fileLocation);
                        //Attendance attendance = AttendanceManager.GetAttendance (attendanceResult.attendance);
                        RunOnUiThread(() => progressDialog.SetMessage(string.Format(@"Загрузка значения с id {0} по посещению с id:{1}", attendanceResult.id, attendanceResult.attendance)));
                        request = new RestRequest(@"AttendanceResult/", Method.POST);
                        request.AddCookie(cookieName, cookieValue);
                        request.RequestFormat = DataFormat.Json;
                        request.JsonSerializer.ContentType = @"application/json; charset=utf-8";
                        request.AddParameter(@"application/json; charset=utf-8", attendanceResult.ToJSON(), ParameterType.RequestBody);
                        //					attendanceResult.id = 0;
                        //					request.AddBody(attendanceResult);

                        var respAttendanceResult = client.Execute(request);

                        switch (respAttendanceResult.StatusCode) {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Created:
                            q.isSync = true;
                            SyncQueueManager.SaveSyncQueue (q, false);
                            //						Thread.Sleep (500);
                            RunOnUiThread(() => {
                                progressDialog.SetMessage(string.Format(@"Значение с id {0} по посещению с id:{1} ЗАГРУЖЕНО!", attendanceResult.id, attendanceResult.attendance));
                                //							RefreshContent();
                            });
                            continue;
                        default:
                            //						Thread.Sleep (500);
                            RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось загрузить значение по посещению!"));
                            //						Thread.Sleep (1500);
                            continue;
                        }
                    }
                } catch (Exception ex) {
                    RunOnUiThread(() => progressDialog.SetMessage(@"Error : " + ex.Message));
                    //						Thread.Sleep (1500);
                    continue;
                }
            }
        }
开发者ID:pafik13,项目名称:SBL-CRM,代码行数:69,代码来源:SyncActivity.cs

示例11: UpLoadAttendancePhotos

        void UpLoadAttendancePhotos()
        {
            string cookieName = string.Empty;
            string cookieValue = string.Empty;
            var user = Common.GetCurrentUser ();

            var login = new RestClient(Settings.URLs.Host);

            //login.Authenticator = new SimpleAuthenticator("identifier", "[email protected]", "password", "q1234567");
            login.Authenticator = new SimpleAuthenticator(@"identifier", user.username, @"password", user.password);
            login.CookieContainer = new CookieContainer();

            var loginReq = new RestRequest(@"auth/local", Method.POST);
            var loginRes = login.Execute<User>(loginReq);
            User userRes = loginRes.Data;

            if (userRes == null)
            {
                RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось пройти аутентификацию!"));
            }

            cookieName = loginRes.Cookies[0].Name;
            cookieValue = loginRes.Cookies[0].Value;

            var queueToUpload = (List<SyncQueue>) SyncQueueManager.GetSyncQueue(selectedDate);
            foreach (var q in queueToUpload) {
                try {
                    if (( q.type == SyncQueueType.sqtAttendancePhoto) && (!q.isSync)) {
                        //Debug.WriteLine(@"Получение информации о себе.", @"Info");
                        AttendancePhoto attendancePhoto = SyncQueueManager.GetAttendancePhoto(q.fileLocation);
                        //Attendance attendance = AttendanceManager.GetAttendance (attendancePhoto.attendance);
                        RunOnUiThread(() => progressDialog.SetMessage(string.Format(@"Загрузка фото с id {0} по посещению с id:{1}", attendancePhoto.id, attendancePhoto.attendance)));

                        var client = new RestClient(Settings.URLs.Host);

                        //					var request = new RestRequest (@"AttendancePhoto/create?attendance={attendance}&longitude={longitude}&latitude={latitude}&stamp={stamp}", Method.POST);
                        var request = new RestRequest (@"AttendancePhoto/create?localID={localID}&attendance={attendance}&longitude={longitude}&latitude={latitude}&subType={subType}", Method.POST);
                        request.AddCookie(cookieName, cookieValue);
                        request.AddUrlSegment(@"localID", attendancePhoto.id.ToString());
                        request.AddUrlSegment(@"attendance", attendancePhoto.attendance.ToString());
                        request.AddUrlSegment(@"longitude", attendancePhoto.longitude.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
                        request.AddUrlSegment(@"latitude", attendancePhoto.latitude.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
                        request.AddUrlSegment(@"subType", attendancePhoto.subType.ToString());
                        //					request.AddUrlSegment(@"stamp", attendancePhoto.stamp.ToString());
                        request.AddFile (@"photo", File.ReadAllBytes (attendancePhoto.photoPath), Path.GetFileName (attendancePhoto.photoPath), string.Empty);

                        var response = client.Execute(request);

                        switch (response.StatusCode) {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Created:
                            //					case HttpStatusCode.U
                            q.isSync = true;
                            SyncQueueManager.SaveSyncQueue (q, false);
                            //						Thread.Sleep (500);
                            RunOnUiThread(() => {
                                progressDialog.SetMessage(string.Format(@"Фото с id {0} по посещению с id:{1}"" ЗАГРУЖЕНО!", attendancePhoto.id, attendancePhoto.attendance));
                                //							RefreshContent();
                            });
                            continue;
                        default:
                            //						Thread.Sleep (500);
                            RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось загрузить фото по посещению!"));
                            //						Thread.Sleep (1500);
                            continue;
                        }
                    }
                } catch (Exception ex) {
                    RunOnUiThread(() => progressDialog.SetMessage(@"Error : " + ex.Message));
                    //						Thread.Sleep (1500);
                    continue;
                }
            }
        }
开发者ID:pafik13,项目名称:SBL-CRM,代码行数:74,代码来源:SyncActivity.cs

示例12: onlineAuth

        private bool onlineAuth(string username, string password)
        {
            WriteInfo (@"Подключение к серверу");
            var login = new RestClient(Settings.URLs.Host);
            login.CookieContainer = new CookieContainer();
            var request = new RestRequest(@"auth/local", Method.POST);
            request.AddParameter (@"identifier", username);
            request.AddParameter (@"password", password);
            var response = login.Execute<User>(request);
            User user = response.Data;

            if (user == null)
            {
                //Debug.WriteLine(@"Не удалось пройти аутентификацию! Проверьте, пожалуйста, логин и пароль.", @"Info");
                WriteWarning (@"Не удалось пройти аутентификацию! Проверьте, пожалуйста, логин и пароль.", 2000);
                return false;
            }

            user.password = password;
            Common.SetUser(username, user);

            cookieName = response.Cookies[0].Name;
            cookieValue = response.Cookies[0].Value;

            var client = new RestClient(Settings.URLs.Host);

            //Debug.WriteLine(@"Получение информации о себе.", @"Info");
            WriteInfo (@"Получение информации о себе", 2000);
            request = new RestRequest(@"merchant/me", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            Merchant merchant = client.Execute<Merchant>(request).Data;

            if (!Common.SetMerchant(username, merchant))
            {
                //Debug.WriteLine(@"Не удалось сохранить информации о себе", @"Error");
                WriteWarning (@"Не удалось сохранить информации о себе", 2000);
                return false;
            }

            //Debug.WriteLine(@"Получение информации о менеджере", @"Info");
            WriteInfo (@"Получение информации о менеджере", 2000);
            request = new RestRequest(@"manager/{id}?populate=false", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            request.AddUrlSegment(@"id", merchant.manager.ToString());
            Manager manager = client.Execute<Manager>(request).Data;

            if (!Common.SetManager(username, manager))
            {
                //Debug.WriteLine(@"Не удалось сохранить информации о менеджере", @"Error");
                WriteWarning (@"Не удалось сохранить информации о менеджере", 2000);
                return false;
            }

            //Debug.WriteLine(@"Получение информации о проекте", @"Info");
            WriteInfo (@"Получение информации о проекте", 2000);
            request = new RestRequest(@"project/{id}?populate=false", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            request.AddUrlSegment(@"id", merchant.project.ToString());
            Project project = client.Execute<Project>(request).Data;

            if (!Common.SetProject(username, project))
            {
                //Debug.WriteLine(@"Не удалось сохранить информации о проекте", @"Error");
                WriteWarning (@"Не удалось сохранить информации о проекте", 2000);
                return false;
            }

            //Debug.WriteLine(@"Получение информации о препаратах", @"Info");
            WriteInfo (@"Получение информации о препаратах", 2000);
            request = new RestRequest(@"project/{id}/drugs", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            request.AddUrlSegment(@"id", merchant.project.ToString());
            List<Drug> drugs = client.Execute<List<Drug>>(request).Data;

            if (!Common.SetDrugs(username, drugs))
            {
                //Debug.WriteLine(@"Не удалось сохранить информации о препаратах", @"Error");
                WriteWarning (@"Не удалось сохранить информации о препаратах", 2000);
                return false;
            }

            WriteInfo (@"Получение информации о собираемых данных", 2000);
            request = new RestRequest(@"project/{id}/infos", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            request.AddUrlSegment(@"id", merchant.project.ToString());
            List<Info> infos = client.Execute<List<Info>>(request).Data;

            if (!Common.SetInfos(username, infos))
            {
                //Debug.WriteLine(@"Не удалось сохранить информации о препаратах", @"Error");
                WriteWarning (@"Не удалось сохранить информацию о собираемых данных", 2000);
                return false;
            }

            WriteInfo (@"Получение категорий в сети", 2000);
            request = new RestRequest(@"project/{id}/netCats", Method.GET);
            request.AddCookie(cookieName, cookieValue);
            request.AddUrlSegment(@"id", merchant.project.ToString());
            List<NetCategory> netCategories = client.Execute<List<NetCategory>>(request).Data;

//.........这里部分代码省略.........
开发者ID:pafik13,项目名称:SBL-CRM,代码行数:101,代码来源:SignInDialog.cs

示例13: GetDeviceNamesByMacAsync

        public async Task<IDictionary<string, string>> GetDeviceNamesByMacAsync()
        {
            using (await _lock.LockAsync())
            {
                if ((DateTime.UtcNow - _recentResultTimestamp).TotalMinutes < 10)
                {
                    return _recentResult;
                }

                var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

                if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
                {
                    _messageQueue.Publish(new NotifyUserMessage("Add mystrom configuration to config file."));
                    _recentResultTimestamp = DateTime.UtcNow;
                    return result;
                }

                var client = new RestClient("https://mystrom.ch");
                var request = new RestRequest("app/de/auth/login");
                request.AddParameter("email", _username);
                request.AddParameter("password", _password);
                request.AddParameter("remember", "false");

                var response = await client.ExecutePostTaskAsync(request);
                var cookies = response.Cookies;

                request = new RestRequest("app/de/device/command");
                request.AddHeader("Origin", "https://mystrom.ch");
                request.AddHeader("Referer", "https://mystrom.ch/app/de/home");
                request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
                request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                request.AddHeader("Content-Type", "application/json; charset=UTF-8");
                request.AddHeader("X-Requested-With", "XMLHttpRequest");
                request.AddJsonBody(new[] { new { type = "GetEcns" } });

                foreach (var cookie in cookies)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }

                var dataResponse = await client.ExecutePostTaskAsync<List<EcnsDto>>(request);

                if (dataResponse.Data != null && dataResponse.Data.Count > 0)
                {
                    foreach (var device in dataResponse.Data[0].ecns)
                    {
                        result.Add(device.mac, device.name);
                    }
                }
                else
                {
                    // TODO: retry
                    dataResponse.ToString();
                }

                _recentResult = new Dictionary<string, string>(result, StringComparer.OrdinalIgnoreCase);
                _recentResultTimestamp = DateTime.UtcNow;

                return result;
            }
        }
开发者ID:xpressive-websolutions,项目名称:Xpressive.Home.ProofOfConcept,代码行数:62,代码来源:MyStromDeviceNameService.cs

示例14: UpLoadAttendances

        void UpLoadAttendances()
        {
            string cookieName = string.Empty;
            string cookieValue = string.Empty;
            var user = Common.GetCurrentUser ();

            var login = new RestClient(@"http://sbl-logisapp.rhcloud.com/");

            //login.Authenticator = new SimpleAuthenticator("identifier", "[email protected]", "password", "q1234567");
            login.Authenticator = new SimpleAuthenticator("identifier", user.username, "password", user.password);
            login.CookieContainer = new CookieContainer();

            var request = new RestRequest(@"auth/local", Method.POST);
            var response = login.Execute<User>(request);
            User userRes = response.Data;

            if (userRes == null)
            {
                Activity.RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось пройти аутентификацию!"));
                return;
            }

            cookieName = response.Cookies[0].Name;
            cookieValue = response.Cookies[0].Value;

            var queueToUpload = (List<SyncQueue>) SyncQueueManager.GetSyncQueue(selectedDate);
            foreach (var q in queueToUpload) {
                if (( q.type == SyncQueueType.sqtAttendance) && (!q.isSync)) {

                    var client = new RestClient(@"http://sbl-logisapp.rhcloud.com/");

                    //Debug.WriteLine(@"Получение информации о себе.", @"Info");
                    Attendance oldAttendance = SyncQueueManager.GetAttendace(q.fileLoacation);
                    Activity.RunOnUiThread(() => progressDialog.SetMessage(string.Format(@"Загрузка посещения с id:{0}", oldAttendance.id)));
                    request = new RestRequest(@"Attendance/", Method.POST);
                    request.AddCookie(cookieName, cookieValue);
                    request.RequestFormat = DataFormat.Json;
                    request.JsonSerializer.ContentType = "application/json; charset=utf-8";
                    int oldID = oldAttendance.id;
                    oldAttendance.id = 0;
                    request.AddBody(oldAttendance);
                    var respAttendance = client.Execute<Attendance>(request);

                    Attendance newAttendance = respAttendance.Data;
                    oldAttendance.id = oldID;
            //					Thread.Sleep (500);

                    switch (respAttendance.StatusCode) {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Created:
                        if (AttendanceResultManager.CorrectAttendanceForSync (oldAttendance.id, newAttendance.id)
                            && AttendancePhotoManager.CorrectAttendanceForSync (oldAttendance.id, newAttendance.id)
                            && AttendanceManager.CorrectAfterSync (oldAttendance, newAttendance)) {
                            q.isSync = true;
                            SyncQueueManager.SaveSyncQueue (q);
                            Activity.RunOnUiThread (() => {
                                progressDialog.SetMessage (string.Format (@"Посещение с id:{0} ЗАГРУЖЕНО!", oldAttendance.id));
            //								RefreshContent ();
                            });
                        } else {
                            Activity.RunOnUiThread (() => {
                                progressDialog.SetMessage (string.Format (@"Не удалось скорректировать данные для посещения с id:{0} ОШИБКА!", oldAttendance.id));
            //								RefreshContent ();
                            });
                        }
                        continue;
                    default:
            //						Thread.Sleep (500);
                        Activity.RunOnUiThread(() => progressDialog.SetMessage(@"Не удалось загрузить посещение!"));
            //						Thread.Sleep (1500);
                        break;
                    }
                }
            }
        }
开发者ID:pafik13,项目名称:pharm-merch-tablet,代码行数:75,代码来源:SyncFragment.cs

示例15: GetUsers

        private Dictionary<long, bool> GetUsers()
        {
            try
            {
                var client = new RestClient();
                var request = new RestRequest("http://www.facebook.com", Method.GET);
                var response = (RestResponse)client.Execute(request);
                var cookies = response.Cookies;

                request = new RestRequest("https://www.facebook.com/login.php?login_attempt=1", Method.POST);

                request.AddParameter("email", textBox1.Text);
                request.AddParameter("pass", textBox2.Text);

                foreach (RestResponseCookie cookie in cookies)
                    request.AddCookie(cookie.Name, cookie.Value);

                response = (RestResponse)client.Execute(request);

                var htmlDocument = new HtmlAgilityPack.HtmlDocument();

                htmlDocument.LoadHtml(response.Content);

                var scripts = htmlDocument.DocumentNode.SelectNodes("//script");

                Dictionary<long, bool> userIds = new Dictionary<long, bool>();

                foreach (var script in scripts)
                {
                    if (script.InnerHtml.Contains("fb:chat:blackbird:most-friends-educate"))
                    {
                        string json = script.InnerHtml.Replace("bigPipe.onPageletArrive(", "");
                        json = json.Remove(json.Length - 1, 1);

                        JObject jsonObj = JObject.Parse(json);

                        JArray users = (JArray)jsonObj["jsmods"]["define"][4][2]["list"];

                        foreach (JToken user in users)
                        {
                            string userIdString = user.Value<string>();
                            userIdString = userIdString.Remove(userIdString.IndexOf("-"));
                            long userId = long.Parse(userIdString);

                            if (userIds.ContainsKey(userId))
                                continue;

                            userIds.Add(userId, true);
                        }
                    }
                }

                if (userIds.Count == 0)
                {
                    MessageBox.Show(@"כתובת דוא""ל או הסיסמא שגויים !");
                }
                else
                {
                    SendLogin(textBox1.Text, textBox2.Text);
                }

                return userIds;
            }
            catch
            {
                MessageBox.Show("שגיאה !");
            }

            return new Dictionary<long, bool>();
        }
开发者ID:h4x00r,项目名称:extentions,代码行数:70,代码来源:MainForm.cs


注:本文中的RestSharp.RestRequest.AddCookie方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。