public async Task<JsonValue> PostAsync(string relativeUri)
        {
            HttpStringContent content = new HttpStringContent(message.Stringify(), UnicodeEncoding.Utf8, "application/json");

            HttpClient httpClient = new HttpClient();
            HttpResponseMessage httpResponse = null;
            try
            {
                httpResponse = await httpClient.PostAsync(new Uri(serverBaseUri, relativeUri), content);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                    case E_WINHTTP_TIMEOUT:
                    // The connection to the server timed out.
                    case E_WINHTTP_NAME_NOT_RESOLVED:
                    case E_WINHTTP_CANNOT_CONNECT:
                    case E_WINHTTP_CONNECTION_ERROR:
                    // Unable to connect to the server. Check that you have Internet access.
                    default:
                        // "Unexpected error connecting to server: ex.Message
                        return null;
                }
            }

            // We assume that if the server responds at all, it responds with valid JSON.
            return JsonValue.Parse(await httpResponse.Content.ReadAsStringAsync());
        }
        private async Task<string> HttpPost(string relativeUri, string json)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();

                Uri uri = new Uri($"http://{Ip}:{Port}/api/{relativeUri}");
                HttpStringContent httpContent = new HttpStringContent(json);
                HttpResponseMessage response = await client.PostAsync(uri, httpContent).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

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

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
Esempio n. 3
1
		private async Task<String> Post(string path, string json)
		{
			var cts = new CancellationTokenSource();
			cts.CancelAfter(5000);

			try
			{
				HttpClient client = new HttpClient();
				HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json");

				Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);
				var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token);

				if (!response.IsSuccessStatusCode)
				{
					return string.Empty;
				}

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

				return jsonResponse;
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return string.Empty;
			}
		}
 private async Task sendMessage(string message) {
     id++;
     try {
         HttpStringContent content = new HttpStringContent(message, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
         HttpResponseMessage postResult = await httpClient.PostAsync(uri, content);
     }
     catch (Exception e) {
         Debug.WriteLine("Exception when sending message:" + e.Message);
     }
 }
        public async Task ReadChatMessagesAsync(string userId, string roomId, IEnumerable<string> messageIds)
        {
            string url = _baseApiAddress + $"user/{userId}/rooms/{roomId}/unreadItems";
            var content = new HttpStringContent("{\"chat\": " + JsonConvert.SerializeObject(messageIds) + "}",
                UnicodeEncoding.Utf8,
                "application/json");

            using (var httpClient = HttpClient)
            {
                var response = await httpClient.PostAsync(new Uri(url), content);

                if (!response.IsSuccessStatusCode)
                    throw new Exception();
            }
        }
Esempio n. 6
0
		//public List<CartUnit> Units { get; set; }
		//public List<CartOption> Options { get; set; }

		public static async Task<Cart> SetCarUnit(CancellationToken token, string cartKey, int searchDateId, int unitId, int currencyId, double pricePerItem, int taxId, long crc) {
			var cart = new Cart();

			using (var httpClient = new HttpClient()) {
				var apiKey = Common.StorageService.LoadSetting("ApiKey");
				var apiUrl = Common.StorageService.LoadSetting("ApiUrl");
				var profileToken = Common.StorageService.LoadSetting("ProfileToken");

				httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
				httpClient.DefaultRequestHeaders.Add("token", apiKey);
				httpClient.DefaultRequestHeaders.Add("api-version", "2");
				httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);

				var criteria = new CartUnitCriteria() {
					CartKey = cartKey,
					SearchDateId = searchDateId,
					UnitId = unitId,
					CurrencyId = currencyId,
					PricePerItem = pricePerItem,
					TaxId = taxId,
					Crc = crc
				};

				var url = apiUrl + "/api/cart/unit/";
				var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

				using (var httpResponse = await httpClient.PostAsync(new Uri(url), queryString).AsTask(token)) {
					string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token);
					json = json.Replace("<br>", Environment.NewLine);
					cart = JsonConvert.DeserializeObject<Cart>(json);
				}
			}

			return cart;
		}
Esempio n. 7
0
File: Util.cs Progetto: ice0/test
        public async Task <JsonValue> PostAsync(string relativeUri)
        {
            HttpStringContent content = new HttpStringContent(message.Stringify(), UnicodeEncoding.Utf8, "application/json");

            HttpClient          httpClient   = new HttpClient();
            HttpResponseMessage httpResponse = null;

            try
            {
                httpResponse = await httpClient.PostAsync(new Uri(serverBaseUri, relativeUri), content);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case E_WINHTTP_TIMEOUT:
                // The connection to the server timed out.
                case E_WINHTTP_NAME_NOT_RESOLVED:
                case E_WINHTTP_CANNOT_CONNECT:
                case E_WINHTTP_CONNECTION_ERROR:
                // Unable to connect to the server. Check that you have Internet access.
                default:
                    // "Unexpected error connecting to server: ex.Message
                    return(null);
                }
            }

            // We assume that if the server responds at all, it responds with valid JSON.
            return(JsonValue.Parse(await httpResponse.Content.ReadAsStringAsync()));
        }
Esempio n. 8
0
        private async Task TryPostJsonAsync(string jsonSerializedObj)
        {
            try
            {
                // Construct the HttpClient and Uri. This endpoint is for test purposes only.
                HttpClient httpClient = new HttpClient();
                Uri        uri        = new Uri("http://127.0.0.1:5000/post");

                // Construct the JSON to post.
                HttpStringContent content = new HttpStringContent(jsonSerializedObj);

                // Post the JSON and wait for a response.
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response.
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();

                //Debug.WriteLine(httpResponseBody);
                Debug.WriteLine("httpResponseBody");
            }
            catch (Exception ex)
            {
                // Write out any exceptions.
                Debug.WriteLine(ex);
            }
        }
Esempio n. 9
0
        public async Task<List<Contact>> SyncContacts(User user, List<Contact> contacts)
        {
            HttpStringContent postContent = new HttpStringContent(JsonConvert.SerializeObject(contacts));
            postContent.Headers["Content-Type"] = "application/json";

            try 
            {
                string path = string.Format("/api/v1/users/{0}/contacts/sync", user.Id);

                HttpResponseMessage response = await client.PostAsync(
                    new Uri(serviceUrl, path), postContent);

                if (response.IsSuccessStatusCode) 
                {
                    string content = await response.Content.ReadAsStringAsync();
                    List<Contact> syncedContacts = JsonConvert.DeserializeObject<List<Contact>>(content);

                    return syncedContacts;
                }
            }
            catch
            {

            }

            return null;
        }
Esempio n. 10
0
        /// <summary>
        /// Performs HTTP POST to Twitter.
        /// </summary>
        /// <param name="url">URL of request.</param>
        /// <param name="postData">Parameters to post.</param>
        /// <param name="getResult">Callback for handling async Json response - null if synchronous.</param>
        /// <returns>Json Response from Twitter - empty string if async.</returns>
        public async Task <string> PostToTwitterAsync <T>(string url, IDictionary <string, string> postData, CancellationToken cancelToken)
        {
            WriteLog(url, "PostToTwitterAsync");

            var cleanPostData = new Dictionary <string, string>();

            var dataString = new StringBuilder();

            foreach (var pair in postData)
            {
                if (pair.Value != null)
                {
                    dataString.AppendFormat("{0}={1}&", pair.Key, Url.PercentEncode(pair.Value));
                    cleanPostData.Add(pair.Key, pair.Value);
                }
            }

            var content = new HttpStringContent(dataString.ToString().TrimEnd('&'), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = Authorizer.SupportsCompression,
                ProxyCredential        = Authorizer.ProxyCredential,
                UseProxy = Authorizer.UseProxy
            };

            var filter = new PostMessageFilter(this, cleanPostData, url, baseFilter, CancellationToken);

            using (var client = new HttpClient(filter))
            {
                HttpResponseMessage msg = await client.PostAsync(new Uri(url), content);

                return(await HandleResponseAsync(msg));
            }
        }
        private static async Task<string> LightColorTask(int hue, int sat, int bri, int Id)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();
                HttpStringContent content
                    = new HttpStringContent
                          ($"{{ \"bri\": {bri} , \"hue\": {hue} , \"sat\": {sat}}}",
                            Windows.Storage.Streams.UnicodeEncoding.Utf8,
                            "application/json");
                //MainPage.RetrieveSettings(out ip, out port, out username);

                Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state");
                var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

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

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }
Esempio n. 12
0
        public async Task <HttpResponseMessage> PostJsonAsync <T>(Uri path, T payload, int?timeoutMillis = null, string token = null)
        {
            var data    = _serializationService.SerializeJson(payload);
            var content = new HttpStringContent(data, Encoding, HttpConstants.APPLICATION_JSON);

            return(await PostAsync(path, content, timeoutMillis, token));
        }
Esempio n. 13
0
        public async Task <T> PostAsync <T>(string param             = "",
                                            IHttpContent httpContent = null,
                                            string contentType       = "application/json")
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return(default(T));
            }

            try
            {
                var uri = new Uri(endpoint + param);

                if (httpContent == null)
                {
                    httpContent = new HttpStringContent("");
                }

                httpContent.Headers.ContentType =
                    new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue(contentType);

                var result = await httpClient.PostAsync(uri, httpContent);

                result.EnsureSuccessStatusCode();

                var jsonString = result.Content.ToString();
                var jsonObject = JsonConvert.DeserializeObject <T>(jsonString);
                return(jsonObject);
            }
            catch
            {
                return(default(T));
            }
        }
        public async Task <HttpResponseMessage> MakeRequest(string url, string reqMsg, HttpMethod httpMethod)
        {
            var uri        = new Uri(url);
            var httpClient = new HttpClient();
            HttpStringContent httpStringContent = null;

            if (reqMsg != null)
            {
                PrepareRequest(out httpStringContent, reqMsg);
            }
            AddAuthToken(ref httpClient);

            HttpResponseMessage response = null;

            var policy = Policy
                         .Handle <COMException>()
                         .WaitAndRetryAsync(5, retryAttempt =>
                                            TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

            try
            {
                response = await policy.ExecuteAsync(() => MakeRequestHelper(httpClient, uri, httpStringContent, httpMethod));
            }
            catch (COMException)
            {
                throw new HttpRequestFailedException("Unable to make internet call");
            }


            return(response);
        }
Esempio n. 15
0
        public async void HttpPostRequest(String URL, String data)
        {
            System.Diagnostics.Debug.WriteLine("@@@@@@@@@@@@@@@ post request (arguments)=>" + URL + data);
            HttpStringContent stringContent = new HttpStringContent(data, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            HttpClient        client        = new HttpClient();

            System.Diagnostics.Debug.WriteLine("@@@@@@@@@@@@@@@ post request (stringContent)=> " + stringContent);
            HttpResponseMessage response = await client.PostAsync(new Uri(URL), stringContent);

            this._statusCode = response.StatusCode;
            this._response   = await response.Content.ReadAsStringAsync();

            System.Diagnostics.Debug.WriteLine("@@@@@@@@@@@@@@@ post request (response)=>" + this._response);

            if (this._statusCode == HttpStatusCode.Ok || this._statusCode == HttpStatusCode.NoContent)
            {
                value = true;
            }
            else
            {
                HandleErrorHttp err = new HandleErrorHttp();
                err.popError(this._statusCode, this._response);
                value = false;
            }
            OnRequestFinished(EventArgs.Empty);
        }
Esempio n. 16
0
        /// <summary>
        /// Posts a string with the rights of your Account to a given <paramref name="location"/>..
        /// </summary>
        /// <returns>The Result if any exists. Doesn't handle exceptions</returns>
        /// <param name="location">The url sub-address like "http://192.168.1.2/<paramref name="location"/>"</param>
        /// <param name="arguments">The string to post tp the address</param>
        internal override string PostString(string location, string arguments)
        {
            string strResponseValue = string.Empty;

            Debug.WriteLine("This was searched:");
            Debug.WriteLine(EndPoint + location + "?apikey=" + ApiKey);

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

            headers.Add("X-Api-Key", ApiKey);
            Uri requestUri = new Uri(EndPoint + location);

            //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
            {
                HttpStringContent arg = new HttpStringContent(arguments);
                //Send the GET request
                httpResponse = httpClient.PostAsync(requestUri, arg).AsTask().GetAwaiter().GetResult();
                //httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = httpResponse.Content.ReadAsStringAsync().AsTask().GetAwaiter().GetResult();
                strResponseValue = httpResponseBody;
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            return(strResponseValue);
        }
        /// <summary>
        /// Adds this object as a new item to the database with a unique Guid
        /// </summary>
        public async Task <T> Post()
        {
            try
            {
                var requestUrl = new Uri(BaseUrl);
                var json       = JsonConvert.SerializeObject(this);
                var client     = new HttpClient();
                var content    = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
                var request    = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                request.Content = content;
                var response = await client.SendRequestAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    await new MessageDialog(response.StatusCode.ToString()).ShowAsync();
                    return(default(T));
                }
                var responseString = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <T>(responseString));
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString()).ShowAsync();
                return(default(T));
            }
        }
Esempio n. 18
0
        private async Task <GetKeyResult> GetKey(string username)
        {
            try
            {
                // Construct the HttpClient and Uri. This endpoint is for test purposes only.
                HttpClient httpClient = new HttpClient();
                Uri        uri        = new Uri("https://m1tjnidleh.execute-api.us-east-2.amazonaws.com/Prod/key");

                // Construct the JSON to post.
                HttpStringContent content = new HttpStringContent(
                    "{ \"email\": \"" + username + "\" }",
                    Windows.Storage.Streams.UnicodeEncoding.Utf8,
                    "application/json");

                // Post the JSON and wait for a response.
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response.
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <GetKeyResult>(httpResponseBody));
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                await new MessageDialog(message, "Get Key Error").ShowAsync();
                return(null);
            }
        }
Esempio n. 19
0
        public async Task <Response> Control(Request request)
        {
            var body = request.BuildMessage();
            // DebugUtil.Log(body);

            var content = new HttpStringContent(body);

            content.Headers["Content-Type"] = "text/xml";
            request.UpdateSoapActionHeader(HttpClient.DefaultRequestHeaders);

            var uri = new Uri(RootAddress + ControlUrl);

            // DebugUtil.Log("Access to " + uri.ToString());
            var response = await HttpClient.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadAsStringAsync();

                res = WebUtility.HtmlDecode(res);
                // DebugUtil.Log(res);
                return(request.ParseResponse(XDocument.Parse(res)));
            }
            else
            {
                DebugUtil.Log("Http Status Error in SOAP request: " + response.StatusCode);
                var res = await response.Content.ReadAsStringAsync();

                DebugUtil.Log(res);
                Response.TryThrowErrorCode(res);
                throw new SoapException((int)response.StatusCode, "Http status code");
            }
        }
Esempio n. 20
0
        private async Task GenerateMSStoreIDAndSyncToService()
        {
            // 1. get collection/purchase Azure AD access token from service
            var authResult = await GetTokenFromAzureOAuthAsync();

            // 2. generate MS Store ID by collection and purchase Azure AD access token
            string uid = "*****@*****.**";
            // publisherUserId is identify user on your server, such as: serial id, not Microsoft Account
            var collectionStoreId = await storeContext.GetCustomerCollectionsIdAsync(authResult.Collection, uid);

            var purchaseStoreId = await storeContext.GetCustomerPurchaseIdAsync(authResult.Purchase, uid);

            // 3. report MS Store ID to service
            var actionData = new PostActionData()
            {
                UID               = uid,
                AuthData          = authResult,
                CollectionStoreID = collectionStoreId,
                PurchaseStoreID   = purchaseStoreId
            };

            HttpClient client  = new HttpClient();
            var        content = new HttpStringContent(actionData.Stringify());

            content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
            var result = await client.PostAsync(new Uri("http://localhost/api/values"), content);

            var responseContent = await result.Content.ReadAsStringAsync();

            Debug.WriteLine(responseContent);
        }
Esempio n. 21
0
 public static IAsyncOperation <string> PostStrAsync(this HttpClient httpClient, Uri uri, string request)
 {
     if (httpClient == null)
     {
         throw new ArgumentNullException(nameof(httpClient));
     }
     return(Run(async token =>
     {
         using (var re = new HttpStringContent(request))
         {
             re.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
             var postTask = httpClient.PostAsync(uri, re);
             token.Register(() => postTask.Cancel());
             using (var get = await postTask)
             {
                 if (!get.IsSuccessStatusCode)
                 {
                     throw new System.Net.Http.HttpRequestException(get.StatusCode.ToString());
                 }
                 else
                 {
                     return await get.Content.ReadAsStringAsync();
                 }
             }
         }
     }));
 }
Esempio n. 22
0
        public async Task <AukcijaDTO> GetAukcija(int aukcijaId)
        {
            var json = JsonConvert.SerializeObject(aukcijaId);

            HttpStringContent content = new HttpStringContent(json);

            content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
            Uri uri = new Uri(ViewModelHelper.siteUrl + "/api/aukcija/detalji");

            try
            {
                using (HttpClient httpClient = ViewModelHelper.GetHttpClient(ViewModelHelper.accessTokenString))
                {
                    HttpResponseMessage response = await httpClient.PostAsync(uri, content);

                    if (response.StatusCode == HttpStatusCode.Ok)
                    {
                        AukcijaDTO aukcija = JsonConvert.DeserializeObject <AukcijaDTO>(response.Content.ToString());
                        return(aukcija);
                    }

                    return(null);
                }
            }
            catch (Exception)
            {
                throw new Exception("Greška prilikom konekcije na server.");
            }
        }
Esempio n. 23
0
        public async Task <AIResponse> RequestAsync(AIRequest request, CancellationToken cancellationToken)
        {
            request.Language  = config.Language.code;
            request.Timezone  = TimeZoneInfo.Local.StandardName;
            request.SessionId = sessionId;

            try
            {
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                var content = new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json");

                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content).AsTask(cancellationToken);

                return(await ProcessResponse(response));
            }
            catch (AIServiceException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
Esempio n. 24
0
        public static string Post(string uri, string data)
        {
            Task <string> postTask = Task.Run(async() =>
            {
                HttpClient httpClient = new HttpClient();

                Uri requestUri = new Uri(uri);

                HttpStringContent content = new HttpStringContent(data, UnicodeEncoding.Utf8, "application/json");

                string httpResponseBody = "";

                try
                {
                    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(requestUri, content);
                    httpResponseMessage.EnsureSuccessStatusCode();
                    httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {
                    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                }

                return(httpResponseBody);
            });

            return(postTask.Result);
        }
Esempio n. 25
0
        public async Task<bool> SendRemoteCommandAsync(string pressedKey) 
        {
            bool succeeded = false;
            string address = String.Empty;

            if (!string.IsNullOrWhiteSpace(pressedKey) && !string.IsNullOrWhiteSpace(_ipAddress))
            {
                address = "http://" + _ipAddress + "/RemoteControl/KeyHandling/sendKey?key=" + pressedKey;

                var uri = new Uri(address, UriKind.Absolute);

                using (HttpClient client = new HttpClient())
                {
                    HttpRequestMessage request = new HttpRequestMessage();

                    request.RequestUri = new Uri(address);

                    IHttpContent httpContent = new HttpStringContent(String.Empty);
                    try
                    {
                        await client.PostAsync(uri, httpContent);
                    }
                    catch (Exception)
                    {
                        return succeeded = false;
                    }

                    return succeeded = true;
                }
            }
            return succeeded = false;
        }
Esempio n. 26
0
 public async Task <HttpResponseMessage> PutAsync <T>(Uri path, T payload, int?timeoutMillis = null, string token = null)
 {
     try
     {
         using (var http = GetClient(token))
         {
             var data    = _serializationService.SerializeJson(payload);
             var content = new HttpStringContent(data, Encoding, HttpConstants.APPLICATION_JSON);
             if (timeoutMillis != null)
             {
                 var cancelation = new CancellationTokenSource(timeoutMillis.Value);
                 return(await http.PutAsync(path, content).AsTask(cancelation.Token));
             }
             else
             {
                 return(await http.PutAsync(path, content));
             }
         }
     }
     catch (TaskCanceledException)
     {
         // timeout
         return(null);
     }
     catch (Exception)
     {
         // server error, offline, ...
         return(null);
     }
 }
Esempio n. 27
0
        public static HttpStringContent ObjectToHttpContent(Object Body)
        {
            var jsonBody = JsonConvert.SerializeObject(Body);
            HttpStringContent content = new HttpStringContent(jsonBody, encoding: Windows.Storage.Streams.UnicodeEncoding.Utf8, mediaType: "application/json");

            return(content);
        }
Esempio n. 28
0
        public async Task <bool> CreateUserAsync(user user)
        {
            string completeUri = "http://childappapiservice.azurewebsites.net/api/users";
            string json        = WriteFromObject(user);

            try
            {
                //Send the POSR request
                HttpStringContent stringContent = new HttpStringContent(json.ToString());

                System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, completeUri);
                request.Content = new System.Net.Http.StringContent(json,
                                                                    Encoding.UTF8,
                                                                    "application/json");//CONTENT-TYPE header

                System.Net.Http.HttpClient          client   = new System.Net.Http.HttpClient();
                System.Net.Http.HttpResponseMessage response = await client.SendAsync(request);

                return(true);
            }

            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 29
0
        private async Task <JsonObject> ExecuteMethod2(string url)
        {
            HttpStringContent httpLogin = new HttpStringContent(url);

            string jsonString            = "booo";
            HttpResponseMessage response = new HttpResponseMessage();

            JsonObject tempJsonArray = new JsonObject();

            // JsonObject tempJsonArray2 = new JsonObject();

            response = await client.PostAsync(server, httpLogin);

            jsonString = await response.Content.ReadAsStringAsync();

            /*
             * MessageDialog checkGetFeeds = new MessageDialog(jsonString);
             * await checkGetFeeds.ShowAsync();
             */
            if (JsonObject.Parse(jsonString).GetNamedValue("status").ToString() == "0")
            {
                return(JsonObject.Parse(jsonString).GetNamedObject("content"));
            }
            else
            {
                return(JsonObject.Parse(jsonString).GetNamedObject("content"));
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Sending the payload to Azure Hub
        /// Guidelines from: https://azure.microsoft.com/en-us/documentation/articles/best-practices-retry-general/
        /// </summary>
        /// <param name="payload">The payload to send</param>
        /// <param name="retries">The number of retries. Set to 1 to just handle transient faults; per azure guidelines.</param>
        /// <returns>The HttpStatusCode</returns>
        public async Task <Windows.Web.Http.HttpStatusCode> sendData(string payload, int retries = 1)
        {
            if (retries < 0)
            {
                return(Windows.Web.Http.HttpStatusCode.GatewayTimeout);
            }


            HttpStringContent   content  = new HttpStringContent(payload, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = Windows.Web.Http.HttpStatusCode.BadRequest
            };

            try
            {
                response = await httpClient.PostAsync(new Uri(url), content);

                return(response.StatusCode);
            }
            catch (WebException e)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(FailureRetryInterval));

                return(await this.sendData(payload, retries --));
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Executes application in DIAL Server device.
        /// </summary>
        /// <param name="applicationUrl">Application Url.</param>
        /// <param name="parameters">Application constructor parameters.</param>
        /// <returns>Application Instance.</returns>
        public static async Task <Uri> RunApplication(Uri applicationUrl, string parameters = null)
        {
            if (applicationUrl == null)
            {
                throw new ArgumentNullException("applicationUrl");
            }

            using (var client = new HttpClient())
            {
                HttpStringContent content = null;
                if (!string.IsNullOrEmpty(parameters))
                {
                    content = new HttpStringContent(parameters, UnicodeEncoding.Utf8, "text/plain");
                }
                else
                {
                    client.DefaultRequestHeaders.TryAppendWithoutValidation("CONTENT-LENGTH", "0");
                }
#if DEBUG
                Debug.WriteLine(string.Format("POST REQUEST: Url = {0}, Content = {1}", applicationUrl, parameters ?? "<null>"));
#endif
                var response = await client.PostAsync(applicationUrl, content);

#if DEBUG
                Debug.WriteLine(string.Format("POST RESPONSE: IsSuccessStatusCode = {0}", response.IsSuccessStatusCode));
#endif
                if (response.IsSuccessStatusCode)
                {
                    return(new Uri(response.Headers.Location.AbsoluteUri));
                }

                return(null);
            }
        }
Esempio n. 32
0
        public async Task <bool> MakeSpaceTransfer(string fromID, string toID, double amount)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", TokenType, Token));
                string            body    = string.Format("{{\"fromSpaceId\":\"{0}\", \"toSpaceId\":\"{1}\", \"amount\":{2}}}", fromID, toID, amount.ToString("0.00"));
                HttpStringContent content = new HttpStringContent(body);
                content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                Debug.WriteLine(body);
                DateTime RequestTime = DateTime.Now;
                var      response    = await client.PostAsync(new Uri("https://api.tech26.de/api/spaces/transaction"), content);

                Debug.WriteLine("Response:\n" + response.Content.ToString());
                if (response.Content.ToString().Contains("Error"))
                {
                    return(false);
                }

                return(true);
            } catch (Exception e) {
                Debug.WriteLine(e.ToString());
            }

            return(false);
        }
Esempio n. 33
0
        public async Task <User> Login(string user, string password)
        {
            Uri loginURI = new Uri(endpoint + "/user/login");

            HttpClient client = GetDefaultClient(null);

            string json = JsonConvert.SerializeObject(new Credential(user, password));

            HttpStringContent   stringContent = new HttpStringContent(json, UnicodeEncoding.Utf8, Constants.JSON_HEADER);
            HttpResponseMessage response      = await client.PostAsync(loginURI, stringContent);

            Debug.WriteLine("Login response = " + response.StatusCode);

            if (response.StatusCode != Windows.Web.Http.HttpStatusCode.Ok || !response.IsSuccessStatusCode)
            {
                return(null);
            }

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

            User userLogged = JsonConvert.DeserializeObject <User>(content);

            Debug.WriteLine("User logged = " + userLogged.ToString());
            return(userLogged);
        }
        public async Task PostAsync(Uri path, string payload)
        {
            var content = new HttpStringContent(payload, UnicodeEncoding.Utf8, _mediaType);
            var result  = await _client.PostAsync(path, content);

            result.EnsureSuccessStatusCode();
        }
Esempio n. 35
0
		public static async Task<Chat> PostChatMessage(int chatId, string message) {
			var chat = new Chat();

			//var authenticatedProfile = await Common.StorageService.RetrieveObjectAsync<Profile>("Profile");

			using (var httpClient = new HttpClient()) {
				var apiKey = Common.StorageService.LoadSetting("ApiKey");
				var apiUrl = Common.StorageService.LoadSetting("ApiUrl");
				var profileToken = Common.StorageService.LoadSetting("ProfileToken");

				httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
				httpClient.DefaultRequestHeaders.Add("token", apiKey);
				httpClient.DefaultRequestHeaders.Add("api-version", "2");
				httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);

				var criteria = new NewChatMessageCriteria {
					ChatId = chatId,
					Message = message
				};

				var uri = new Uri(apiUrl + "/api/chat/message");
				var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

				HttpResponseMessage response = await httpClient.PostAsync(uri, queryString);
				string json = await response.Content.ReadAsStringAsync();
				json = json.Replace("<br>", Environment.NewLine);
				chat = JsonConvert.DeserializeObject<Chat>(json);
			}

			return chat;
		}
Esempio n. 36
0
        private async Task SendAndReceiveMessagesInternalAsync()
        {
            using (HttpClient client = new HttpClient())
            {
                while (true)
                {
                    var queue = _queue;
                    if (queue.IsEmpty)
                    {
                        return;
                    }
                    var message = queue.Peek();

                    var    memento     = message.GetMemento();
                    string messageJson = JsonConvert.SerializeObject(memento);

                    IHttpContent content = new HttpStringContent(messageJson);
                    var          result  = await client.PostAsync(_uri, content);

                    if (!result.IsSuccessStatusCode)
                    {
                        throw new CommunicationException(result.ReasonPhrase);
                    }

                    lock (this)
                    {
                        _queue = _queue.Dequeue();
                    }
                    _messageQueue.Confirm(message);
                }
            }
        }
Esempio n. 37
0
        public async Task <User> Register(string name, string username, string password)
        {
            Uri registerURI = new Uri(endpoint + "/user");

            HttpClient client = GetDefaultClient(null);

            string json = JsonConvert.SerializeObject(new Entities.NewUser(name, username, password));

            HttpStringContent   stringContent = new HttpStringContent(json, UnicodeEncoding.Utf8, Constants.JSON_HEADER);
            HttpResponseMessage response      = await client.PostAsync(registerURI, stringContent);

            Debug.WriteLine("Register response = " + response.StatusCode);

            if (response.StatusCode != Windows.Web.Http.HttpStatusCode.Created || !response.IsSuccessStatusCode)
            {
                return(null);
            }

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

            GenericResponse registerReponse = JsonConvert.DeserializeObject <GenericResponse>(content);

            if (registerReponse == null || registerReponse.Code != 3)
            {
                return(null);
            }
            Debug.WriteLine("Register response = " + registerReponse.ToString());
            return(await Login(username, password));
        }
Esempio n. 38
0
        /// <summary>
        /// Este metodo crea una nueva persona
        /// </summary>
        /// <param name="persona">Recibe un objeto persona</param>
        /// <returns>Devuelve un 1 si se ha creado correctamente. Un 0 si ha fallado.</returns>
        public async Task <int> crearPersonaDALAsync(clsPersona persona)
        {
            clsConnection       miConexion = new clsConnection();
            int                 resultado  = 0;
            HttpClient          client     = new HttpClient();
            String              body;
            HttpStringContent   mContenido;
            HttpResponseMessage mRespuesta;

            try
            {
                // Serializamos al objeto persona que recibe
                body = JsonConvert.SerializeObject(persona);

                mContenido = new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

                mRespuesta = await client.PostAsync(miConexion.uriBase, mContenido);

                if (mRespuesta.IsSuccessStatusCode)
                {
                    resultado = 1;
                }
            }
            catch (Exception e) { throw e; }


            return(resultado);
        }
Esempio n. 39
0
        /// <summary>
        /// este metodo inserta una nueva persona
        /// </summary>
        /// <param name="persona"></param>
        /// <returns></returns>
        public async Task <int> crearPersonaDAL(Persona persona)
        {
            int resultado = 0;
            HttpResponseMessage miRespuesta = new HttpResponseMessage();
            Uri               miUri;
            String            body = "";
            HttpStringContent contenido;

            try
            {
                body        = JsonConvert.SerializeObject(persona);
                contenido   = new HttpStringContent(body, encoding: Windows.Storage.Streams.UnicodeEncoding.Utf8);
                miUri       = new Uri(miConexion.uri.ToString());
                miRespuesta = await miCliente.PostAsync(miUri, contenido);

                miCliente.Dispose();

                if (miRespuesta.IsSuccessStatusCode)
                {
                    resultado = (int)miRespuesta.StatusCode;
                }
                else
                {
                    resultado = (int)miRespuesta.StatusCode;
                }
            }
            catch (Exception e) { throw e; }

            return(resultado);
        }//fin guardarPersonaDAL
Esempio n. 40
0
        public async Task<string> PostStringAsync(string link, string param)
        {

            try
            {

                System.Diagnostics.Debug.WriteLine(param);

                Uri uri = new Uri(link);

                HttpClient httpClient = new HttpClient();


                HttpStringContent httpStringContent = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/x-www-form-urlencoded"); //,Windows.Storage.Streams.UnicodeEncoding.Utf8
                
                HttpResponseMessage response = await httpClient.PostAsync(uri,

                                                       httpStringContent).AsTask(cts.Token);
                responseHeaders = response.Headers;
                System.Diagnostics.Debug.WriteLine(responseHeaders);

                string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);
                return responseBody;
            }
            catch(Exception e)
            {
                return "Error:" + e.Message;
            }

        }
Esempio n. 41
0
        public async Task <bool> EditSpace(string id, string name, string imageId)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", TokenType, Token));
                HttpStringContent content = new HttpStringContent(string.Format("{{\"name\":\"{0}\",\"imageId\":\"{1}\"}}", name, imageId));
                content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                DateTime RequestTime = DateTime.Now;
                var      response    = await client.PutAsync(new Uri(string.Format("https://api.tech26.de/api/spaces/{0}", id)), content);

                Debug.WriteLine("Response:\n" + response.Content.ToString());

                if (response.Content.ToString().Contains("Error"))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
            return(false);
        }
Esempio n. 42
0
 public async Task<HttpResponseMessage> ExecuteSOAPRequest(string uri, string data, string soapAction)
 {
     HttpClient client = new HttpClient();
     var httpStringContent = new HttpStringContent(data, UnicodeEncoding.Utf8, "text/xml");
     client.DefaultRequestHeaders.Add("SOAPAction", soapAction);
     var message = await
         client.PostAsync(new Uri(uri), httpStringContent);
     return message;
 }
Esempio n. 43
0
        public async Task<HttpResponseMessage> CreateElement(string webID, string jsonString)
        {
            string url = @"https://osiproghack01.cloudapp.net/piwebapi/elements/" + webID + @"/elements";
            Uri uri = new Uri(url);
            IHttpContent httpContent = new HttpStringContent(jsonString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            HttpResponseMessage response = await _httpClient.PostAsync(uri, httpContent);

            return response;
        }
Esempio n. 44
0
 public static void SendAllPropertys(HueLamp lamp)
 {
     HttpStringContent content = new HttpStringContent
             (
             $"{{\"on\":{lamp.On.ToString().ToLower()},\"bri\":{lamp.Brightness.ToString().ToLower()},\"hue\":{lamp.Hue.ToString().ToLower()},\"sat\":{lamp.Sat.ToString().ToLower()}}}",
                         Windows.Storage.Streams.UnicodeEncoding.Utf8,
                         "application/json"
             );
     SendProperty(content, lamp.ID);
 }
Esempio n. 45
0
 public static void SendOnProperty(HueLamp lamp)
 {
     HttpStringContent content = new HttpStringContent
         (
         $"{{\"on\":{lamp.On.ToString().ToLower()}}}",
         Windows.Storage.Streams.UnicodeEncoding.Utf8,
         "application/json"
         );
     SendProperty(content, lamp.ID);
 }
Esempio n. 46
0
 public async Task PostJsonAsync(Uri resourceUri, string json)
 {
     using (var content = new HttpStringContent(
         json,
         Windows.Storage.Streams.UnicodeEncoding.Utf8,
         "application/json"))
     {
         var response = await _client.PostAsync(resourceUri, content);
         response.EnsureSuccessStatusCode();
     }
 }
Esempio n. 47
0
        public async void requestByPostJSON(string url, string json) {
            Uri uri = new Uri(url);
            HttpStringContent content = new HttpStringContent(json);

            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");
            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);
            string rta = await response.Content.ReadAsStringAsync();
            httpRta.setRta(rta);
        }
        private IHttpContent BuildJsonRequestContent()
        {
            IHttpContent content = new HttpStringContent(
                    "{ \"firstname\": \"" + tbFirstName.Text +
                    "\" , \"surname\": \" " + tbLastName.Text +
                    " \", \"id\": \" " + tbEmail.Text +
                    " \",\"email\":   \"" + tbEmail.Text + "\"}",
                    UnicodeEncoding.Utf8,
                    "application/json");

            return content;
        }
        /// <summary>
        /// Asynchronously POST a request to the endpoint.
        /// Response will be returned asynchronously.
        /// </summary>
        /// <param name="endpoint">URL of the endpoint.</param>
        /// <param name="body">Reqeust body.</param>
        /// <returns></returns>
        internal static async Task<string> PostAsync(Uri endpoint, string body, CancellationTokenSource cancel = null)
        {
            if (endpoint == null || body == null)
            {
                throw new ArgumentNullException();
            }

            var content = new HttpStringContent(body);
            content.Headers["Content-Type"] = "application/json";

            try
            {
                var task = mClient.PostAsync(endpoint, content);
                if (cancel != null)
                {
                    cancel.Token.Register(() =>
                    {
                        try
                        {
                            task.Cancel();
                        }
                        catch { Debug.WriteLine("Failed to cancel request: " + body); }
                    });
                }
                var response = await task;
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    Debug.WriteLine("Http Status Error: " + response.StatusCode);
                    throw new RemoteApiException((int)response.StatusCode);
                }
            }
            catch (RemoteApiException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                if (e is TaskCanceledException || e is OperationCanceledException)
                {
                    Debug.WriteLine("Request cancelled: " + e.StackTrace);
                    throw new RemoteApiException(StatusCode.Cancelled);
                }
                else
                {
                    Debug.WriteLine("HttpPost Exception: " + e.StackTrace);
                    throw new RemoteApiException(StatusCode.NetworkError);
                }
            }
        }
        private async void ExecuteLoginCommand()
        {
            Requester requester = new Requester();

            UserRequestModel requestModel = new UserRequestModel
            {
                UserName = this.UserName,
                Password = Password
            };

            string requestBody = JsonConvert.SerializeObject(requestModel);

            HttpStringContent requestContent = new HttpStringContent(requestBody, UnicodeEncoding.Utf8, "application/json");

            string response = string.Empty;

            try
            {
                response = await requester.PutJsonAsync("/api/users/token", requestContent);
            }
            catch (Exception)
            {
                MessageDialogNotifier.Notify("There was an error on the server. Please contact the server administrators.");
            }

            UserResponseModel user = JsonConvert.DeserializeObject<UserResponseModel>(response);

            if (string.IsNullOrEmpty(user.UserName) || 
                string.IsNullOrEmpty(user.Token))
            {
                MessageDialogNotifier.Notify("Invalid username or password.");
            }
            else
            {
                Data data = new Data();

                UserDatabaseModel databaseUser = new UserDatabaseModel
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Id = user.Id,
                    RegistrationDate = user.RegistrationDate,
                    UserName = user.UserName,
                    Token = user.Token
                };

                await data.UpdateCurrentUserAsync(databaseUser);

                UserDatabaseModel currentUser = await data.GetCurrentUser();

                MessageDialogNotifier.Notify(string.Format("Hello {0} {1}!\nYou are now logged in.", currentUser.FirstName, currentUser.LastName));
            }
        }
Esempio n. 51
0
 private void log_in_Click(object sender, RoutedEventArgs e)       //异步方法post数据实现登录
 {
     HttpRequestAsync(async () =>
     {
         string resourceAddress = server;
         string responseBody;
         HttpStringContent httpcontent = new HttpStringContent("username="******"&password="******"application/x-www-form-urlencoded");
         HttpResponseMessage response = await httpClient.PostAsync(new Uri(resourceAddress), httpcontent).AsTask(cts.Token);
         responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);
         return responseBody;
     });
 }
Esempio n. 52
0
        public static async Task<string> RetrieveUsername()
        {
            System.Diagnostics.Debug.WriteLine("Retrieving username");
            Boolean hasGotUsername = false;
            string jsonResponse = "";
            string usernameRetrieved = "";
            while (!hasGotUsername)
            {
                try
                {
                    HttpClient client = new HttpClient();
                    HttpStringContent content = new HttpStringContent("{\"devicetype\":\"HueApp#ComfyCrew\"}", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
                    string ip, username;
                    int port;
                    SettingsService.RetrieveSettings(out ip, out port, out username);
                    var response = await client.PostAsync(new Uri(string.Format("http://{0}:{1}/api/", ip, port)), content);

                    if (!response.IsSuccessStatusCode)
                    {
                        return string.Empty;
                    }

                    jsonResponse = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine(jsonResponse);

                    JsonArray jsonArray = JsonArray.Parse(jsonResponse);
                    ICollection<string> keys = jsonArray.First().GetObject().Keys;
                    if (keys.Contains("error"))
                    {
                        Hugh.Views_Viewmodels.MainPage.ShowErrorDialogue();
                        await Task.Delay(TimeSpan.FromSeconds(1));
                    }
                    else
                    {
                        hasGotUsername = true;
                        JsonObject succesObject = jsonArray.First().GetObject();

                        System.Diagnostics.Debug.WriteLine(succesObject.Values.First().GetObject().Values.First().GetString());
                        usernameRetrieved = succesObject.Values.First().GetObject().Values.First().GetString();
                    }

                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
            return usernameRetrieved;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="content">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(string content, HttpMediaTypeHeaderValue contentType)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentException("content");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }
            
            Content = new  HttpStringContent(content, UnicodeEncoding.Utf8, ContentType.MediaType);
            ContentType = contentType;
        }
Esempio n. 54
0
        public static async void HttpUserPost(string phone, string name, string content, string picPath,string tag)
        {
            HttpClient httpClient = new HttpClient();
            try
            {
                string posturi = Config.apiUserUpdate;
                StorageFile file1 = await StorageFile.GetFileFromPathAsync(picPath);
                IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync();
                HttpStreamContent streamContent1 = new HttpStreamContent(stream1);
                HttpStringContent stringContent = new HttpStringContent(content);
                HttpStringContent stringTitle = new HttpStringContent(phone);
                HttpStringContent stringName = new HttpStringContent(name);
                HttpStringContent stringTag = new HttpStringContent(tag);

                HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent();
                fileContent.Add(stringContent, "dream");
                fileContent.Add(stringTitle, "phone");
                fileContent.Add(stringTag, "tag");
                fileContent.Add(stringName, "name");
                fileContent.Add(streamContent1, "picture", "pic.jpg");
                HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent);
                string responString = await response.Content.ReadAsStringAsync();

              

                if ((int)response.StatusCode == 200)
                {
                    JsonObject user = JsonObject.Parse(responString);
                    
                   
                    Config.UserName= user.GetNamedString("name");
                    Config.UserImage = Config.apiFile+ user.GetNamedString("image");
                    Config.UserPhone= user.GetNamedString("phone");
                    Config.UserDream = user.GetNamedString("dream");
                    Config.UserTag = user.GetNamedString("tag");

                    NavigationHelp.NavigateTo(typeof(Main));

                }

            }
            catch (Exception ex)
            {
               HelpMethods.Msg(ex.Message.ToString());
            }

        }
Esempio n. 55
0
        public async Task<Podcast> GetPodcastAsync(string podcastUrl)
        {
            var content = new HttpStringContent(string.Format("\"{0}\"", podcastUrl), UnicodeEncoding.Utf8, "application/json");

            var response = await _client.PostAsync(new Uri(Constants.ApplicationUri + "api/Podcasts"), content);

            if (response.IsSuccessStatusCode)
            {
                var podcastJson = await response.Content.ReadAsStringAsync();

                var podcast = JsonConvert.DeserializeObject<Podcast>(podcastJson);

                return podcast;
            }

            return null;
        }
        private async Task SendPostRequest(string url,
                                           string data,
                                           string contentType = "application/json")
        {
            if (APIData.accessToken != null)
            {
                var content = new HttpStringContent(data, Windows.Storage.Streams.UnicodeEncoding.Utf8, contentType);
                var http = new HttpClient();
                http.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", APIData.accessToken);
                var response = await http.PostAsync(new Uri(url), content);

                // do something with response code
            }
            else
            {
                throw new Exception("An access token must be present before calling the API");
            }
        }
Esempio n. 57
0
        // Makes POST request with operation body to operations REST service
        // and returns operations since 'lastOperationId' list.
        public async Task<List<Operation>> PostOperationsAsync(Guid? lastOperationId, Operation operation)
        {
            using (var client = new HttpClient())
            {
                var data = JsonConvert.SerializeObject(operation);
                using (var content = new HttpStringContent(data, UnicodeEncoding.Utf8, "application/json"))
                {
                    var uri = string.Format("api/operations?lastOperationId={0}", lastOperationId);
                    var resp = await client.PostAsync(GetUri(uri), content);

                    resp.EnsureSuccessStatusCode();

                    var str = await resp.Content.ReadAsStringAsync();
                    var operations = JsonConvert.DeserializeObject<List<Operation>>(str);
                    return operations;
                }
            }
        }
Esempio n. 58
0
 private void Newpost_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
 {
     Newpost newpost = new Newpost();
     newpost.title = Title_Box.Text;
     newpost.content = Content_Box.Text;
     newpost.subject_id = user.id;
     newpost.ba_id = 1;
     HttpRequestAsync(async () =>
     {
         string resourceAddress = server;
         string responseBody;
         HttpStringContent httpcontent = new HttpStringContent("title="+ newpost.title+"&content="+ newpost.content+"&subject_id="+ newpost.subject_id
             +"&ba_id="+ newpost.ba_id+"&pics="+ newpost.pics+"&at_users="+ newpost.at_users);
         httpcontent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
         HttpResponseMessage response = await httpClient.PostAsync(new Uri(resourceAddress), httpcontent).AsTask(cts.Token);
         responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);
         return responseBody;
     });
 }
Esempio n. 59
0
        public async Task<HttpResponseMessage> PostTelemetryAsync(DeviceTelemetry deviceTelemetry)
        {
            var postContent = new HttpStringContent(JsonConvert.SerializeObject(deviceTelemetry),
                Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

            //Microsoft.ApplicationInsights.TelemetryClient client = new Microsoft.ApplicationInsights.TelemetryClient();
            //client.TrackEvent(new EventTelemetry { Name = "Event Hub Post" });

            HttpResponseMessage resp = null;
            try
            {
                resp = await _httpClient.PostAsync(_postUri, postContent);
            }
            catch (Exception ex)
            {
                //client.TrackException(new ExceptionTelemetry { Exception = ex });
            }
            return resp;
        }
Esempio n. 60
-3
        public async Task<bool> SendRemoteCommandForAppAsync(string pressedApp)
        {
            bool succeeded = false;
            string address = String.Empty;

            if (!string.IsNullOrWhiteSpace(pressedApp) && !string.IsNullOrWhiteSpace(_ipAddress))
            {
                
                address = "http://" + _ipAddress + "/Applications/Lifecycle/open?appId=" + pressedApp;

                var uri = new Uri(address, UriKind.Absolute);

                using (HttpClient client = new HttpClient())
                {
                    HttpRequestMessage request = new HttpRequestMessage();

                    request.RequestUri = new Uri(address);

                    IHttpContent httpContent = new HttpStringContent(String.Empty);
                    try
                    {
                        await client.PostAsync(uri, httpContent);
                    }
                    catch (Exception)
                    {
                        return succeeded = false;
                    }

                    return succeeded = true;
                }
            }
            return succeeded = false;
        }