Example #1
0
        async void getWeather(string location)
        {
            string url = "http://v.juhe.cn/weather/index?cityname=" + location + "&dtype=xml&format=2&key=8f9462857e209325b1ffc655525ce3a5";
            Uri    uri = new Uri(url);

            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            var    httpResponseMessage             = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                httpResponseMessage = await httpClient.GetAsync(uri);

                httpResponseMessage.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
            }
            catch (Exception exception)
            {
                httpResponseBody = "ERROR " + exception.HResult.ToString("X") + "Message " + exception.Message;
            }

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(httpResponseBody);
            XmlNodeList list = xmlDocument.GetElementsByTagName("weather");
            IXmlNode    node = list.Item(0);

            weather.Text = location + ":" + node.InnerText;
        }
        protected internal override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            cancel.ThrowIfCancellationRequested();

            Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);

            RTHttpRequestMessage rtRequest = await ConvertRequestAsync(request).ConfigureAwait(false);

            RTHttpResponseMessage rtResponse = await _next.SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false);

            // Update in case of redirects
            request.RequestUri = rtRequest.RequestUri;

            HttpResponseMessage response = ConvertResponse(rtResponse);

            response.RequestMessage = request;

            s_diagnosticListener.LogHttpResponse(response, loggingRequestId);

            return(response);
        }
Example #3
0
        public async Task <string> GetResponseBodyAsync(Uri requestUri)
        {
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            var    headers = httpClient.DefaultRequestHeaders;
            string header  = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }

            return(httpResponseBody);
        }
Example #4
0
        public async Task <List <Produtos> > getListAsync()
        {
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            List <Produtos>             produtos   = new List <Produtos>();
            var headers    = httpClient.DefaultRequestHeaders;
            Uri requestUri = new Uri("http://julianoblanco-001-site3.ctempurl.com/WebService/ProductList");

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                List <Produtos> list = JsonConvert.DeserializeObject <List <Produtos> >(httpResponseBody);
                foreach (Produtos p in list)
                {
                    if (p.AR == true)
                    {
                        produtos.Add(p);
                    }
                }
                return(produtos);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                return(null);
            }
        }
Example #5
0
        public static async Task <OutTable[]> GetMsgAsync(string contact)
        {
            string completeUri = "https://function-queue-connect.azurewebsites.net/api/HttpGET-outTable-CSharp1?code=smvhBz/DBsmNUDqf7/TIhjZ1IMBSo77LwpSbhG2I9CsGCw1D6sNLkg==&&name="
                                 + who_am_i + "$" + contact;

            Uri requestUri = new Uri(completeUri);

            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                OutTable[] msg = JsonConvert.DeserializeObject <OutTable[]>(httpResponseBody);
                return(msg);
            }

            catch (Exception ex)
            {
                return(null);
            }
        }
Example #6
0
        async Task DeleteTags(string url)
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(new Uri(url));

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                //Hidde some tags
                httpResponseBody = Regex.Replace(httpResponseBody, "div id=\"YDC-UH\"", "div id=\"YDC-UH\" hidden");
                httpResponseBody = Regex.Replace(httpResponseBody, "<div id=\"YDC-Side-Stack\"", "<div id=\"YDC-Side-Stack\" hidden");
                httpResponseBody = Regex.Replace(httpResponseBody, "<div class=\"c", "<div hidden class=\"c");
                httpResponseBody = Regex.Replace(httpResponseBody, "<div id=\"YDC-Bottom\" ", "<div id=\"YDC-Bottom\" hidden ");
                //httpResponseBody = Regex.Replace(httpResponseBody, "<button class=\"D.ib.", "<button hidden class=\"D.ib.");
            }
            catch (Exception ex)
            {
                httpResponseBody =
                    "<!DOCTYPE html> <html> <head> <link href=\"https://fonts.googleapis.com/css?family=Roboto\" rel=\"stylesheet\"> </head> <body style=\"background-color:BlueViolet;\"> <div style=\"width: 300px; height: 300px; position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -150px;\"><center><font color=\"white\"><h1 style=\"font-family: 'Roboto', sans-serif;\">" +
                    "</ h1 ></ font ></ center ></ div > </ body > </ html > " + "Error: " + ex.HResult.ToString("X") +
                    " Message: " + ex.Message.TrimEnd() + ".";
            }
            WebView1.NavigateToString(httpResponseBody);
        }
        public async System.Threading.Tasks.Task <string> GetDeviceInformation(string url)
        {
            string result     = string.Empty;
            Uri    contentUri = null;

            try
            {
                contentUri = new Uri(url);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception while creating uri for: " + url + " exception: " + ex.Message);
                return(result);
            }

            HttpBaseProtocolFilter RootFilter = new HttpBaseProtocolFilter();

            RootFilter.CacheControl.ReadBehavior  = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            RootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            var client = new Windows.Web.Http.HttpClient(RootFilter);

            try
            {
                Windows.Web.Http.HttpResponseMessage response = await client.GetAsync(contentUri, Windows.Web.Http.HttpCompletionOption.ResponseContentRead);

                response.EnsureSuccessStatusCode();
                result = await response.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + e.Message);
            }

            return(result);
        }
Example #8
0
        public static async void SendUri()
        {
            var localSettings = ApplicationData.Current.LocalSettings;

            try
            {
                Dictionary <string, string> pairs = new Dictionary <string, string>();
                pairs.Add("ChannelUri", channel.Uri.ToString());
                pairs.Add("check_uri", "true");
                Windows.Web.Http.HttpFormUrlEncodedContent formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
                Windows.Web.Http.HttpClient          client            = new Windows.Web.Http.HttpClient();
                Windows.Web.Http.HttpResponseMessage response          = await client.PostAsync(new Uri("http://" + backendUrl + "notifications/wns/wns.php" + finalUrl, UriKind.Absolute), formContent);

                string result = await response.Content.ReadAsStringAsync();

                JsonObject json       = JsonObject.Parse(result);
                bool       uri_exists = json.GetNamedBoolean("uri_exists");
                if (!uri_exists)
                {
                    localSettings.Values["ChannelUri"] = channel.Uri.ToString();
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// Checks if the username exists in the database
        /// </summary>
        /// <param name="userName">The username string</param>
        private async Task GetUserByUserName(string userName)
        {
            string httpResponseBody;

            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri($"http://localhost:54493/api/UserProfiles/user/{userName}");

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            httpResponseBody = "";

            httpResponse = await httpClient.GetAsync(requestUri);

            httpResponse.EnsureSuccessStatusCode();
            httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

            if (httpResponseBody == "")
            {
                statusMessage.Text = "This user does not exist";
                return;
            }
            ActiveUser = JsonConvert.DeserializeObject <UserProfile>(httpResponseBody);
            CheckUserPassword(ActiveUser);
        }
Example #10
0
        internal static async Task Request()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request.
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                await APITempSave(httpResponseBody);
            }
            catch (Exception ex)
            {
            }
        }
        public async void CoolifyAsync(string s, ObservableCollection <CoolName> coolNames, ProgressBar progbar)
        {
            Uri coolURI = new Uri(BaseURI + CoolServiceURI + s);

            //List<CoolName> coolNames = new List<CoolName>();
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(coolURI);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                JObject jsonObject = JObject.Parse(httpResponseBody);
                coolNames.Clear();
                foreach (var x in jsonObject)
                {
                    coolNames.Add(new CoolName(x.Key, x.Value.ToString()));
                }
                progbar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                coolNames.Clear();
                coolNames.Add(new CoolName("Error", "Maybe the remote server's down 😭"));
                coolNames.Add(new CoolName("Error", "Check if https://cool-name-api.glitch.me/ is working."));
                coolNames.Add(new CoolName("Error", "Check your internet connection"));
                coolNames.Add(new CoolName("Error", ex.Message.ToString()));
                progbar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
        }
        /// <summary>
        /// Fetch response from API
        /// </summary>
        /// /// <param name="uri">The Uri</param>
        public async Task <string> GetResultFromAPI(string uri)
        {
            try
            {
                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
                var headers = httpClient.DefaultRequestHeaders;
                Uri requestShoppingListsUri = new Uri(uri);
                Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
                string httpResponseBody = "";

                httpResponse = await httpClient.GetAsync(requestShoppingListsUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                OfflineModus = false;
                topText.Text = "";
                return(httpResponseBody);
            }
            catch (Exception ex)
            {
                MessageToast("Couldn't establish DB connection");
                OfflineModus          = true;
                topText.Text          = "OFFLINE MODE";
                MyList.ItemsSource    = UserShoppingLists;
                BtnRefresh.Visibility = Visibility.Visible;
                return(null);
            }
        }
        /// <summary>
        /// Converts the received response message.
        /// </summary>
        /// <param name="response">The request message to be transformed.</param>
        /// <param name="cancellationToken">The operation cancellation token.</param>
        /// <returns>The Task representing the asynchronous operation.</returns>
        private static async Task <HttpResponseMessage> ConvertResponse(
            Windows.Web.Http.HttpResponseMessage response,
            CancellationToken cancellationToken)
        {
            // Convert the response
            var converted = new HttpResponseMessage((HttpStatusCode)(int)response.StatusCode)
            {
                ReasonPhrase   = response.ReasonPhrase,
                RequestMessage = await WindowsHttpMessageHandler
                                 .ConvertRequest(response.RequestMessage, cancellationToken)
                                 .ConfigureAwait(false),
                Content = await WindowsHttpMessageHandler.ConvertContent(response.Content, cancellationToken)
                          .ConfigureAwait(false),
                Version = WindowsHttpMessageHandler.GetVersion(response.Version)
            };

            // Copy headers
            foreach (var header in response.Headers)
            {
                converted.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            // Return the converted message
            return(converted);
        }
Example #14
0
        public async Task GetGamesData(string search, int offset)
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add headers
            httpClient.DefaultRequestHeaders.Add("X-Mashape-Key", "aCbxpIpyLomshOig8RGZl7c7pKXGp1Mc7l5jsnl4I2aQIyU11X");                       //Custom header

            httpClient.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json")); //Accept header

            //Search parameterized uri
            string uri        = "https://igdbcom-internet-game-database-v1.p.mashape.com/games/?fields=name%2Csummary%2Cfirst_release_date%2Ccover.url&limit=10&offset=" + offset + "&order=name%3Adesc&search=" + search;
            Uri    requestUri = new Uri(uri);

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                queryResponse = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                queryResponse = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
Example #15
0
        public async Task <dynamic> httpGet(String address)
        {
            Uri uri = new System.Uri(mainApi + address);

            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            dynamic httpResponseBody = "";

            try
            {
                Debug.WriteLine("HttpGet attempt for: " + uri.ToString());
                //Send the GET request
                httpResponse = await httpClient.GetAsync(uri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                return(httpResponseBody);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            Debug.WriteLine("HttpGet null");
            return(null);
        }
        public static async Task <GameDescriptionAndRating> GetGameConfigFomServer(AppDataContext appDataContext)
        {
            JsonObject jsonParameter = ToJsonForGetExpansions(appDataContext);
            string     parameter     = jsonParameter.Stringify();

            var fullUrl = new System.Text.StringBuilder();

            fullUrl.Append(WebService.webUrl);
            fullUrl.Append("?action=GET&values=");
            fullUrl.Append(parameter.Replace(" ", "%20"));

            try
            {
                using (var client = new Windows.Web.Http.HttpClient())
                    using (var request = new Windows.Web.Http.HttpRequestMessage())
                    {
                        request.RequestUri = new System.Uri(fullUrl.ToString());
                        using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask())
                        {
                            if (responseMessage.IsSuccessStatusCode)
                            {
                                string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask();

                                GameDescriptionAndRating description = WebService.GetGameDescriptionFromJson(strResult);
                                System.Diagnostics.Debug.WriteLine("Get Response from server:");
                                System.Diagnostics.Debug.WriteLine(strResult);
                                return(description);
                            }
                        }
                    }
            } catch (System.Exception)
            {
            }
            return(null);
        }
        public static async Task SendGameConfigToServer(AppDataContext appDataContext)
        {
            GameDescription gameDescription = appDataContext.GetGameConfig().gameDescription;

            JsonObject json      = WebService.ToJson(gameDescription, appDataContext.DeckRating.Value);
            string     parameter = json.Stringify();

            var fullUrl = new System.Text.StringBuilder();

            fullUrl.Append(WebService.webUrl);
            fullUrl.Append("?action=RECORD&values=");
            fullUrl.Append(parameter.Replace(" ", "%20"));

            try
            {
                using (var client = new Windows.Web.Http.HttpClient())
                    using (var request = new Windows.Web.Http.HttpRequestMessage())
                    {
                        request.RequestUri = new System.Uri(fullUrl.ToString());
                        using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask())
                        {
                            if (responseMessage.IsSuccessStatusCode)
                            {
                                string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask();

                                System.Diagnostics.Debug.WriteLine("RECORD Reponse from server:");
                                System.Diagnostics.Debug.WriteLine(strResult);
                            }
                        }
                    }
            }
            catch (System.Exception)
            { }
        }
Example #18
0
        /// <summary>
        ///     Downloads songs from local storage
        /// </summary>
        /// <param name="localIp">IP of the local machine</param>
        async void DownloadFromLocalhost()
        {
            var i = 1;
            // Whatever the localhost ip is
            var    localIp  = "http://192.168.178.18:8888";
            string audioURL = localIp + "/music/" + i + ".mp3";

            while (this.URLExists(audioURL))
            {
                var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                myFilter.AllowUI = false;
                Windows.Web.Http.HttpClient          client = new Windows.Web.Http.HttpClient(myFilter);
                Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(audioURL));

                // Saving a file with the number
                var file = await KnownFolders.MusicLibrary.CreateFileAsync(i + " song.mp3", CreationCollisionOption.ReplaceExisting);

                using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await result.Content.WriteToStreamAsync(filestream);

                    await filestream.FlushAsync();
                }

                i++;
                audioURL = localIp + "/music/" + i + ".mp3";  //"http://docs.google.com/uc?export=download&id=0B6u8YFm5Y0GeLXRtd2Z6X0RjNTA";
            }
        }
Example #19
0
        private async void ConnectUsingWebHttpClient(string resourceIdentity, Uri resourceUri)
        {
            try
            {
                // Use Windows.Web.Http.HttpClient to access the resource.
                // The code is identical to a normal resource access, except that we create
                // a ThreadNetworkContext around the client.GetAsync() call.

                using (var client = new Windows.Web.Http.HttpClient())
                {
                    // When using Windows.Web.Http.HttpClient, the app is responsible for disallowing connections
                    // to enterprise owned URLs when in personal context.
                    // Otherwise, the app may inadvertently access cached data for a different context.
                    if (!string.IsNullOrEmpty(resourceIdentity) && UsePersonalContext.IsChecked.Value)
                    {
                        rootPage.NotifyUser("This app does not have access to the specified URL in personal context", NotifyType.ErrorMessage);
                        return;
                    }
                    Windows.Web.Http.HttpResponseMessage response = await UsingNetworkContext(resourceIdentity, () => client.GetAsync(resourceUri));

                    rootPage.NotifyUser($"Server response = {(int)response.StatusCode} {response.ReasonPhrase}", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                // Access to the network resource was not successful.
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #20
0
        //Yande的子站的api是相同的
        //public List<Yande_post_json> list;
        #region 通用获取json返回
        public async Task <string> GetWebJsonStringAsync(string uri)
        {
            JS_RequestUri = uri;
            string jsstring;

            try
            {
                using (Windows.Web.Http.HttpClient httpclient = new Windows.Web.Http.HttpClient())
                {
                    using (Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpclient.GetAsync(new Uri(JS_RequestUri)))
                    {
                        httpResponseMessage.EnsureSuccessStatusCode();
                        jsstring = await httpResponseMessage.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                var s             = ex.Message.ToString();
                var messagedialog = new MessageDialog(s);
                messagedialog.Commands.Add(new UICommand("重试", cmd => { }, commandId: 0));
                messagedialog.DefaultCommandIndex = 0;
                var a = await messagedialog.ShowAsync();

                a.Invoked += await chonshiAsync();

                jsstring = null;

                throw;
            }

            return(jsstring);
        }
        public async Task <Uposlenik> validateU()
        {
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            var headers = httpClient.DefaultRequestHeaders;

            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            string url = "http://localhost:50180/Uposleniks/GetAccount?Email=" + EMail + "&Password="******"http://localhost:50180/Potrosacs/GetAccount?Email" + EMail + "&password="******"";

            try
            {
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                string json = httpResponseBody;
                if (json.Contains("Salterusa"))
                {
                    novi = JsonConvert.DeserializeObject <Salterusa>(json);
                }
                else if (json.Contains("Postar"))
                {
                    novi = JsonConvert.DeserializeObject <Postar>(json);
                }
                else if (json.Contains("Administrator"))
                {
                    novi = JsonConvert.DeserializeObject <Administrator>(json);
                }
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            if (novi == null)
            {
                novi = ePosta.Instanca.dajUposlenikaPoMailu(EMail, Pass);
            }
            return(novi);
        }
    protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Windows.Web.Http.HttpClient         client     = new Windows.Web.Http.HttpClient();
        Windows.Web.Http.HttpRequestMessage webRequest = new Windows.Web.Http.HttpRequestMessage
        {
            Method     = ConvertMethod(request.Method),
            RequestUri = request.RequestUri,
            Content    = await ConvertRequestContentAsync(request.Content).ConfigureAwait(false),
        };
        CopyHeaders(request.Headers, webRequest.Headers);
        Windows.Web.Http.HttpResponseMessage webResponse = await client.SendRequestAsync(webRequest)
                                                           .AsTask(cancellationToken)
                                                           .ConfigureAwait(false);

        HttpResponseMessage response = new HttpResponseMessage
        {
            StatusCode     = ConvertStatusCode(webResponse.StatusCode),
            ReasonPhrase   = webResponse.ReasonPhrase,
            Content        = await ConvertResponseContentAsync(webResponse.Content).ConfigureAwait(false),
            RequestMessage = request,
        };

        CopyHeaders(webResponse.Headers, response.Headers);
        return(response);
    }
Example #23
0
        private static async void parseJSON(string url)
        {
            refresh();
            var filter = new HttpBaseProtocolFilter();

            filter.AllowAutoRedirect = false;
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(filter);

            Uri requestUri = new Uri(url);

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            exist = true;

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                result = JsonConvert.DeserializeObject <RootObject>(httpResponseBody);
            }
            catch (Exception ex)
            {
                // Url does not exist
                exist = false;
            }
        }
Example #24
0
        public async void Get_historical(int id_user)
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            Uri requestUri = new Uri("http://businesswallet.fr/Bmb/Get_Historical.php?id_user="******"";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                List <Historical> historicals = JsonConvert.DeserializeObject <List <Historical> >(httpResponseBody);
                foreach (Historical h in  historicals)
                {
                    listOfHistorical.Add(h);
                }

                ListViewHistorical.ItemsSource = listOfHistorical;
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
Example #25
0
        /// <summary>
        /// Checks if input username already exists in database
        /// </summary>
        private async Task CheckUserNameAvailability()
        {
            string httpResponseBody;

            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            var headers    = httpClient.DefaultRequestHeaders;
            Uri requestUri = new Uri($"http://localhost:54493/api/UserProfiles/user/{InputUserName}");

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            httpResponseBody = "";

            httpResponse = await httpClient.GetAsync(requestUri);

            httpResponse.EnsureSuccessStatusCode();
            httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

            if (httpResponseBody == "")
            {
                CreateNewUserProfile();
            }
            else
            {
                statusMessage.Text = "Username is taken";
            }
        }
Example #26
0
        private async void Get(object s, RoutedEventArgs e)
        {
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("http://api.avatardata.cn/Nba/NomalRace?Key=96b12dbac2094f3ea0f14edbbb83d300&dtype=xml");

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            XmlDocument data             = new XmlDocument();
            string      httpResponseBody = "";

            try
            {
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                data.LoadXml(httpResponseBody);
                ConvertToRes(data);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
Example #27
0
        public async static Task <string> GetExercises()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            //Add a user-agent header to the GET request.
            var headers    = httpClient.DefaultRequestHeaders;
            Uri requestUri = new Uri("http://fitness30.azurewebsites.net/api/exercises");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                return(httpResponseBody);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            return("");
        }
        async public void fetchPages()
        {
            using (Windows.Web.Http.HttpClient wc = new Windows.Web.Http.HttpClient())
            {
                var headers    = wc.DefaultRequestHeaders;
                Uri requestUri = new Uri("https://sessions.io/api/3EFGTLHza");

                //Send the GET request asynchronously and retrieve the response as a string.
                Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
                string httpResponseBody = "";

                try
                {
                    //Send the GET request
                    httpResponse = await wc.GetAsync(requestUri);

                    httpResponse.EnsureSuccessStatusCode();
                    httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                    //parse JSON from the server
                    var result = JsonConvert.DeserializeObject <LessonObject>(httpResponseBody);
                    Debug.WriteLine(httpResponseBody);

                    // then what can we do here?
                }
                catch (Exception ex)
                {
                    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                }
            }
        }
Example #29
0
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            //lock the button, avoid multi requests at the same time
            this.btnLogin.IsEnabled = false;

            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Get User
            User user = new User();

            user.username = txtUsername.Text;
            user.password = txtPassword.Password;

            //Set uri
            Uri requestUri = new Uri(App.URL + "/login?username="******"&password="******"";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message);
            }

            string msg;

            if (httpResponseBody == "logged")
            {
                msg = $"login success.";
                await new MessageDialog(msg).ShowAsync();
                //set global userEmail and user
                Globals.userEmail = user.username;
                this.Frame.Navigate(typeof(MainPage));
            }
            else
            {
                msg = $"username/password is wrong.";
                await new MessageDialog(msg).ShowAsync();
            }
            //clear User
            user.username = string.Empty;
            user.password = string.Empty;

            //clear password
            txtPassword.Password = string.Empty;

            //enable the button
            this.btnLogin.IsEnabled = true;
        }
Example #30
0
        public static async void getdata()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request.
            var headers = httpClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }

            CommunicationScreen.Message = httpResponseBody;


            string[] trimresponse = httpResponseBody.Split('"');
            long     timestamp    = Convert.ToInt64(trimresponse[1]);

            DateTime newdatetime = new DateTime(timestamp);
            TimeSpan correction  = new TimeSpan(14, 30, 00);

            newdatetime.Subtract(correction);
            CommunicationScreen.Message += "\r\n\r\n" + string.Format("{0:hh:mm:ss tt}", newdatetime - correction);

            MainPage.newdatetime = newdatetime - correction;
        }
        public static async void getdata()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");
            
            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }

            CommunicationScreen.Message = httpResponseBody;

            
            string[] trimresponse = httpResponseBody.Split('"');
            long timestamp = Convert.ToInt64(trimresponse[1]);

            DateTime newdatetime = new DateTime(timestamp);
            TimeSpan correction = new TimeSpan(14, 30, 00);
            newdatetime.Subtract(correction);
            CommunicationScreen.Message += "\r\n\r\n" + string.Format("{0:hh:mm:ss tt}", newdatetime - correction);

            MainPage.newdatetime = newdatetime - correction;

        }
Example #32
0
    public static async Task<string> GetUrltoHtml(string url)
    {
        Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

        //Add a user-agent header to the GET request. 
        var headers = httpClient.DefaultRequestHeaders;

        //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
        //especially if the header value is coming from user input.
        string header = "ie";
        if (!headers.UserAgent.TryParseAdd(header))
        {
            throw new Exception("Invalid header value: " + header);
        }

        header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
        if (!headers.UserAgent.TryParseAdd(header))
        {
            throw new Exception("Invalid header value: " + header);
        }

        Uri requestUri = new Uri("http://www.contoso.com");

        //Send the GET request asynchronously and retrieve the response as a string.
        Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
        string httpResponseBody = "";

        try
        {
            //Send the GET request
            httpResponse = await httpClient.GetAsync(requestUri);
            httpResponse.EnsureSuccessStatusCode();
            httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
        }
        catch (Exception ex)
        {
            httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
        }
        return httpResponseBody;

    }
        // code from
        //https://msdn.microsoft.com/en-us/library/windows/apps/mt187345.aspx
        async void getUser(int searchQuery)
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri("http://178.62.9.141:5000/datathon/customer/" + searchQuery);

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }

            // custom
            tbkJsonRes.Text = httpResponseBody;
        }
Example #34
0
        private static HttpResponseMessage ConvertResponse(RTHttpResponseMessage rtResponse)
        {
            HttpResponseMessage response = new HttpResponseMessage((Net.HttpStatusCode)rtResponse.StatusCode);
            response.ReasonPhrase = rtResponse.ReasonPhrase;

            // Version
            if (rtResponse.Version == RTHttpVersion.Http11)
            {
                response.Version = new Version(1, 1);
            }
            else if (rtResponse.Version == RTHttpVersion.Http10)
            {
                response.Version = new Version(1, 0);
            }
            else if (rtResponse.Version == RTHttpVersion.Http20)
            {
                response.Version = new Version(2, 0);
            }
            else
            {
                response.Version = new Version(0, 0);
            }

            bool success;

            // Headers
            foreach (KeyValuePair<string, string> headerPair in rtResponse.Headers)
            {
                if (headerPair.Key.Equals(RTHttpClientHandler.HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase))
                {
                    // The Set-Cookie header always comes back with all of the cookies concatenated together. 
                    // For example if the response contains the following:
                    //     Set-Cookie A=1
                    //     Set-Cookie B=2
                    // Then we will have a single header KeyValuePair of Key=”Set-Cookie”, Value=”A=1, B=2”. 
                    // However clients expect these headers to be separated(i.e. 
                    // httpResponseMessage.Headers.GetValues("Set-Cookie") should return two cookies not one 
                    // concatenated together).
                    success = response.Headers.TryAddWithoutValidation(headerPair.Key, GetCookiesFromHeader(headerPair.Value, rtResponse.RequestMessage.RequestUri));
                }
                else
                {
                    success = response.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
                }

                Debug.Assert(success);
            }

            // Content
            if (rtResponse.Content != null)
            {
                var rtResponseStream = rtResponse.Content.ReadAsInputStreamAsync().AsTask().Result;
                response.Content = new StreamContent(rtResponseStream.AsStreamForRead());

                foreach (KeyValuePair<string, string> headerPair in rtResponse.Content.Headers)
                {
                    success = response.Content.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
                    Debug.Assert(success);
                }
            }

            return response;
        }