コード例 #1
0
ファイル: LoginPageVM.cs プロジェクト: visual1993/luiss-loft
        public async Task <User.PersonalizedData> GetDataFromMoodle(string username, string password)
        {
            var pars = new Dictionary <string, string>();

            //username = "";
            //password = "";
            pars.Add("username", username);
            pars.Add("password", password);
            pars.Add("rememberusername", "0");
            pars.Add("anchor", "");

            var cookieHandler  = new NativeCookieHandler();
            var messageHandler = new NativeMessageHandler(false, false, cookieHandler);
            var httpClient     = new HttpClient(messageHandler);

            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
            var content      = new FormUrlEncodedContent(pars);
            var httpResponse =
                await httpClient.PostAsync(new Uri("http://learn.luiss.it/login/index.php"), content);

            var client = GetHttpClient(cookieHandler.Cookies);
            var res    =
                await client.GetAsync(new Uri("http://learn.luiss.it/user/edit.php"));

            var strRes = await res.Content.ReadAsStringAsync();

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(strRes);
                var      nome    = doc.GetElementbyId("id_firstname").GetAttributeValue("value", "");
                var      cognome = doc.GetElementbyId("id_lastname").GetAttributeValue("value", "");
                var      email   = doc.GetElementbyId("id_email").GetAttributeValue("value", "");
                HtmlNode imgDiv  = null;
                var      img     = "";
                try
                {
                    imgDiv = doc.GetElementbyId("fitem_id_currentpicture").ChildNodes[1].ChildNodes[0].ChildNodes[0];
                    if (imgDiv.Attributes.Contains("src"))
                    {
                        img = imgDiv.Attributes["src"].Value;
                    }
                }
                catch {
                }
                return(new User.PersonalizedData
                {
                    Nome = nome,
                    Cognome = cognome,
                    Email = email,
                    ImageUrl = img,
                    LastChange = DateTime.Now
                });
            }
            catch (Exception ex) {
                Visual1993.Console.WriteLine(ex.Message);
                return(null);
            }
        }
コード例 #2
0
        HttpClient CreateClient()
        {
            NativeCookieHandler  cookieHandler = Settings.mNativeCookieHandler;           //new NativeCookieHandler ();
            NativeMessageHandler handler       = new NativeMessageHandler(true, true, cookieHandler)
            {
                UseCookies = true,
            };

            return(new HttpClient(handler));
        }
コード例 #3
0
        private HttpClient GenerateHttpClient()
        {
            this.CookieContainer = new NativeCookieHandler();

            NativeMessageHandler httpClientHandler = new NativeMessageHandler(
                false,
                true,
                this.CookieContainer
                );

            return(new HttpClient(httpClientHandler));
        }
コード例 #4
0
ファイル: PGService.cs プロジェクト: Xammondxxx/PriceGrabber
 public static void Init()
 {
     if (HttpClient != null)
     {
         return;
     }
     HttpCookieHandler  = new NativeCookieHandler();
     HttpMessageHandler = new NativeMessageHandler(true, false, HttpCookieHandler);
     HttpClient         = new HttpClient(HttpMessageHandler, false);
     //httpClient = new HttpClient();
     //HttpClient.Timeout = TimeSpan.FromSeconds(7);
 }
コード例 #5
0
        private void AddCookies(Uri uri, NativeCookieHandler cookieHandler)
        {
            return;

            ICollection <Cookie> cc = Settings.COOKIES;

            Cookie[] array = new Cookie[cc.Count];
            cc.CopyTo(array, 0);
            cookieHandler.SetCookies(array);
//			Debug.WriteLineIf(Debugger.IsAttached, "START added Cookie");
//			foreach (Cookie cookie in cc) {
//				Debug.WriteLineIf(Debugger.IsAttached, "Added Cookie " + uri.AbsoluteUri +": " + cookie.Name + ": " + cookie.Value);
//
//				cookieHandler.Add(uri, new Cookie(cookie.Name, cookie.Value));
//			}
        }
コード例 #6
0
 public static async void CloseSession()
 {
     while (isBusy)
     {
         await Task.Delay(50);
     }
     try
     {
         isBusy             = true;
         HttpClient         = null;
         httpCookieHandler  = null;
         httpMessageHandler = null;
         DependencyService.Get <IAPIHelper>().ClearCookies();
         AppData.Crew = null;
     }
     finally
     {
         isBusy = false;
     }
 }
コード例 #7
0
        public void InitClient(CookieContainer cookieContainer)
        {
            if (client != null)
            {
                client.Dispose();
            }

            if (Device.RuntimePlatform == Device.Android ||
                Device.RuntimePlatform == Device.iOS)
            {
                var cookies = cookieContainer.List();
                cookieHandler = new NativeCookieHandler();
                cookieHandler.SetCookies(cookieContainer.List());

                handler = new NativeMessageHandler(false, false, cookieHandler)
                {
                    AllowAutoRedirect      = true,
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                };
            }
            else
            {
                handler = new HttpClientHandler
                {
                    CookieContainer        = cookieContainer,
                    AllowAutoRedirect      = true,
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                };
            }

            client = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromSeconds(timeout_in_seconds),
                DefaultRequestHeaders =
                {
                    CacheControl = CacheControlHeaderValue.Parse("no-cache, must-revalidate"),
                }
            };

            client.DefaultRequestHeaders.UserAgent.ParseAdd("Tatoeba.Mobile/1.1");
        }
コード例 #8
0
        private HttpClient CreateClient()
        {
            var uri = new Uri(_url, UriKind.Absolute);

            var cookieHandler = new NativeCookieHandler();

            // CustomSSLVerification must be set to true to enable certificate pinning.
            var nativeHandler = new CustomNativeMessageHandler(_connectivityService, throwOnCaptiveNetwork: false, customSSLVerification: true, enableRc4Compatibility: false, cookieHandler: cookieHandler);

            // otherwise we won't be able to handle 304 NotModified ourselves (ie: Terms & Conditions)
            nativeHandler.DisableCaching = true;
            nativeHandler.UseCookies     = false;

            // use only for debug with proxy like Charles application
            //nativeHandler.Proxy = new WebProxy("192.168.12.163", 8888);

            var client = new HttpClient(nativeHandler)
            {
                BaseAddress = uri,
                Timeout     = new TimeSpan(0, 0, 2, 0, 0)
            };

            // When packageInfo is not specified, we use a default value as the useragent
            client.DefaultRequestHeaders.Add("User-Agent", GetUserAgent());
            if (_packageInfo != null)
            {
                client.DefaultRequestHeaders.Add("ClientVersion", _packageInfo.Version);
            }

            if (_sessionId.HasValueTrimmed())
            {
                client.DefaultRequestHeaders.Add("Cookie", "ss-opt=perm; ss-pid=" + _sessionId);
            }
            client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
            client.DefaultRequestHeaders.AcceptCharset.ParseAdd("utf-8");
            client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip");
            client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("deflate");

            return(client);
        }
コード例 #9
0
        public HttpClientProvider()
        {
            var cookieHandler = new NativeCookieHandler();

            cookieHandler.SetCookies(new Cookie[]
            {
                new Cookie("adult", "1", "/", "www.suruga-ya.jp"),
            });


            HttpClient = new HttpClient(new NativeMessageHandler(
                                            throwOnCaptiveNetwork: false,
                                            new TLSConfig
            {
                //DangerousAcceptAnyServerCertificateValidator = true,
                //DangerousAllowInsecureHTTPLoads = true
            },
                                            cookieHandler: cookieHandler)
            {
                UseCookies = true
            });
        }
コード例 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionService"/> class.
        /// </summary>
        public ConnectionService()
        {
            _cookieHandler = new NativeCookieHandler();
            switch (Xamarin.Forms.Device.RuntimePlatform)
            {
            case Xamarin.Forms.Device.Android:
                Client = new HttpClient(DependencyService.Get <IHTTPClientHandlerCreationService>().GetInsecureHandler())
                {
                    MaxResponseContentBufferSize = 25600000,
                    Timeout = TimeSpan.FromMilliseconds(10000),
                };
                break;

            default:
                Client = new HttpClient(new NativeMessageHandler(false, true, _cookieHandler))
                {
                    MaxResponseContentBufferSize = 25600000,
                    Timeout = TimeSpan.FromMilliseconds(10000),
                };
                break;
            }
        }
コード例 #11
0
        private HttpClient CreateClient(bool useNative)
        {
            var cookieHandler = new NativeCookieHandler();
            var client        =
                useNative ? new HttpClient(
                    new NativeMessageHandler(false, false, cookieHandler)
            {
                UseCookies     = false,
                DisableCaching = true,
            }
                    ) :
                new HttpClient(
                    new HttpClientHandler
            {
                UseCookies = false
            })
            ;

            client.MaxResponseContentBufferSize = 5000000000;
            client.Timeout = TimeSpan.FromSeconds(5);

            return(client);
        }
コード例 #12
0
        public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null, SslProtocol? minimumSSLProtocol = null)
#endif
        {
            var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration;

#if XAMARIN_MODERN
			// we cannot do a bitmask but we can set the minimum based on ServicePointManager.SecurityProtocol minimum
			var sp = ServicePointManager.SecurityProtocol;
			if ((sp & SecurityProtocolType.Ssl3) != 0)
				configuration.TLSMinimumSupportedProtocol = SslProtocol.Ssl_3_0;
			else if ((sp & SecurityProtocolType.Tls) != 0)
				configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_0;
			else if ((sp & SecurityProtocolType.Tls11) != 0)
				configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_1;
			else if ((sp & SecurityProtocolType.Tls12) != 0)
				configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_2;
#else
            // System.Net.ServicePointManager.SecurityProtocol provides a mechanism for specifying supported protocol types
            // for System.Net. Since iOS only provides an API for a minimum and maximum protocol we are not able to port
            // this configuration directly and instead use the specified minimum value when one is specified.
            if (minimumSSLProtocol.HasValue) {
                configuration.TLSMinimumSupportedProtocol = minimumSSLProtocol.Value;
            }
#endif

            session = NSUrlSession.FromConfiguration(
                NSUrlSessionConfiguration.DefaultSessionConfiguration, 
                new DataTaskDelegate(this), null);

#if !XAMARIN_MODERN
            this.throwOnCaptiveNetwork = throwOnCaptiveNetwork;
            this.customSSLVerification = customSSLVerification;
#else
            this.AllowAutoRedirect = true;
#endif

            this.DisableCaching = false;
        }
コード例 #13
0
 /// <summary>
 /// Initializes a new instance of the <see
 /// cref="ModernHttpClient.NativeMessageHandler"/> class.
 /// </summary>
 /// <param name="throwOnCaptiveNetwork">If set to <c>true</c> throw on
 /// captive network (ie: a captive network is usually a wifi network
 /// where an authentication html form is shown instead of the real
 /// content).</param>
 /// <param name="sSLConfig">To enable TLS Mutual Authentication</param>
 /// <param name="cookieHandler">Enable native cookie handling.
 /// </param>
 public NativeMessageHandler(bool throwOnCaptiveNetwork, TLSConfig tLSConfig, NativeCookieHandler cookieHandler = null, IWebProxy proxy = null) : base()
 {
 }
コード例 #14
0
 public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null);
コード例 #15
0
 public CustomNativeMessageHandler(IConnectivityService connectivityService, bool throwOnCaptiveNetwork, bool customSSLVerification, bool enableRc4Compatibility, NativeCookieHandler cookieHandler = null)
     : base(throwOnCaptiveNetwork, customSSLVerification, enableRc4Compatibility, cookieHandler)
 {
     _connectivityService = connectivityService;
 }
コード例 #16
0
 /// <summary>
 /// Constructor
 /// </summary>
 public ConnectionService()
 {
     _cookieHandler = new NativeCookieHandler();
     RefreshClient(); //default
 }
コード例 #17
0
        protected async Task ExecuteLoginCommand()
        {
            Error = string.Empty;

            if (Username.Equals(string.Empty) || Password.Equals(string.Empty))
            {
                Error = Settings.MSG_EMPTY_USERNAME_OR_PWD;
                return;
            }

            if (isLoading)
            {
                return;
            }

            IsLoading = true;
            Info      = "We're processing...";

            Settings.UseTreeMenu = UseTreeMenu;

            try {
                var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string> (Settings.WP_USERNAME_FIELD, Username),
                    new KeyValuePair <string, string> (Settings.WP_PWD_FIELD, Password)
                });

                NativeCookieHandler  cookieHandler = Settings.mNativeCookieHandler;               //new NativeCookieHandler ();
                NativeMessageHandler handler       = new NativeMessageHandler(true, true, cookieHandler)
                {
                    UseCookies = true,
                };

                handler.AllowAutoRedirect = false;
                HttpClient client = new HttpClient(handler);

                HttpResponseMessage response = await client.PostAsync(Settings.LoginUrl, content);

                if (response.StatusCode == HttpStatusCode.Redirect)
                {
                    Debug.WriteLine("Redirect: " + response.ToString());
                    Settings.wpLoggedIn = true;
                    Settings.wpUsername = Username;
                    Settings.wpPassword = Password;
                }
                else
                {
                    string resultContent = await response.Content.ReadAsStringAsync();

                    response.EnsureSuccessStatusCode();
                    string responseUri = response.RequestMessage.RequestUri.ToString();
                    Debug.WriteLine(responseUri);
                    Debug.WriteLine(resultContent);
                    if (Settings.LoginUrl.ToLower().Equals(responseUri.ToLower()))
                    {
                        //login failed
                        Error = Settings.MSG_INVALID_USERNAME_OR_PWD;
                    }
                    else
                    {
                        Settings.wpLoggedIn = true;
                        Settings.wpUsername = Username;
                        Settings.wpPassword = Password;
                    }
                }

                if (Settings.wpLoggedIn)
                {
                    if (Settings.CHECK_UPDATE)
                    {
                        var buildDetail = Mvx.Resolve <IBuildDetails>();
                        var respUpdate  = await Service.GetUpdate(new RequestUpdate(buildDetail.OS, buildDetail.VersionCode));

                        if (respUpdate.Update_info != null)
                        {
                            Settings.UpdateInfo = respUpdate;
                            IsLoading           = false;
                            return;
                        }

                        System.Diagnostics.Debug.WriteLine("Build detail os={0} version_code={1}", buildDetail.OS, buildDetail.VersionCode);
                    }
                    //go to profile to get more cookies
                    response = await client.GetAsync(Settings.ProfileUrl);

                    //get user info and gen cookie for json api auth controller
                    var retAuth = await Service.GenrateAuthCookie();

                    if (retAuth != null)
                    {
                        Settings.WP_AuthCookie = retAuth;
                    }
                    else
                    {
                        Settings.WP_AuthCookie = null;
                    }
                }
            } catch (Exception e) {
                Error = Settings.MSG_NETWORK_COMMON;
                                #if DEBUG
                System.Diagnostics.Debug.WriteLine("Login Error: " + e.Message);
                Error += e.ToString();
                                #endif
            }


            Info      = string.Empty;
            IsLoading = false;
        }
        public NativeAndInexorablyUnsecureMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null)
        {
            this.throwOnCaptiveNetwork = throwOnCaptiveNetwork;

            if (customSSLVerification)
            {
                client.SetHostnameVerifier(new HostnameVerifier());
            }
            noCacheCacheControl = (new CacheControl.Builder()).NoCache().Build();
        }
コード例 #19
0
        public static async Task <ApiResponse> ExecuteCommand(ApiCommand command, string[] pars)
        {
            var response = new ApiResponse();

            ReqLog.Add(response);

            // Get command string from commsnd's attribute
            var apiAttr = command.GetAttribute <ApiCommandAttribute>();

            if (apiAttr.ParamCount != pars.Length)
            {
                response.ErrorMessage = "Ошибка формирования запроса к серверу.";
                return(response);
            }

            string url = API_URL;

            response.Request = url + string.Format(apiAttr.FormatString, pars);

            while (isBusy)
            {
                await Task.Delay(200);
            }

            try
            {
                isBusy = true;

                if (HttpClient == null)
                {
                    httpCookieHandler  = new NativeCookieHandler();
                    httpMessageHandler = new NativeMessageHandler(true, false, httpCookieHandler);
                    httpMessageHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                    HttpClient = new HttpClient(httpMessageHandler, false);
                }

                try
                {
                    Debug.WriteLine("Request: {0}", response.Request);
                    var res = await HttpClient.GetAsync(response.Request).ConfigureAwait(false);

                    Debug.WriteLine("Read content");
                    response.Response = await res.Content.ReadAsStringAsync().ConfigureAwait(false);

                    //response.response = await httpClient.GetStringAsync(response.request);
                    Debug.WriteLine("Response: {0}", response.Response);
                    // Обработка напильником, блять!
                    //response.response = response.response.Replace("\"vUser\":[],", string.Empty);

                    if (string.IsNullOrEmpty(response.Response))
                    {
                        response.ErrorMessage = "Сервер не отвечает, попробуйте повторить позже";
                        return(response);
                    }
                    response.RequestDone = true;
                }
                catch (Exception e)
                {
                    response.BoolResult   = false;
                    response.ErrorMessage = "Ошибка отправки запроса на сервер " + Environment.NewLine + e.Message;
                    //GoogleAnalyticsHelper.SendException("MFService:ExecuteCommand " + e.Message, false);
                    return(response);
                }

                try
                {
                    long x = 0;
                    JsonConvert.PopulateObject(response.Response, response);
                    response.BoolResult = response?.Result?.ToUpper() == "TRUE" || response?.Result?.ToUpper() == "OK";
                    if (!response.BoolResult)
                    {
                        if (!string.IsNullOrEmpty(response.Error))
                        {
                            response.ErrorMessage = response.Error;
                        }
                        else if (string.IsNullOrEmpty(response.ErrorMessage))
                        {
                            response.ErrorMessage = "Запрос к серверу вернул отрицательный результат";
                        }
                    }
                    return(response);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    response.BoolResult   = false;
                    response.ErrorMessage = "Ошибка при разборе ответа от сервера";
                    //GoogleAnalyticsHelper.SendException("MFService:ExecuteCommand " + e.Message, false);
                    return(response);
                }
            }
            finally
            {
                isBusy = false;
            }
        }