示例#1
0
        async public Task <Windows.Web.Http.HttpResponseMessage> PostAsync(Windows.Web.Http.HttpStringContent data)
        {
            try
            {
                _connectionProfile = NetworkInformation.GetInternetConnectionProfile();
                NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

                if (_connectionProfile != null && _connectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
                {
                    using (var httpClient = new HttpClient())
                    {
                        httpClient.DefaultRequestHeaders.Accept.Clear();
                        httpClient.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json"));
                        httpClient.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("Content-Type: application/x-www-form-urlencoded"));
                        var token = JsonConvert.DeserializeObject <AccessToken>(ApplicationData.Current.RoamingSettings.Values[Constants.ACCESSTOKEN].ToString());
                        httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", token.Access_Token);

                        return(await httpClient.PostAsync(new Uri(Constants.APIURL), data));
                    }
                }
                else
                {
                    await new MessageDialog("no network access").ShowAsync();
                    return(default(HttpResponseMessage));
                }
            }
            catch (Exception ex)
            {
                new MessageDialog(ex.Message).ShowAsync();
                return(default(HttpResponseMessage));
            }
        }
    public static async Task <UnityPrimitive> CreateObject(UnityPrimitive updatedObject)
#endif
    {
        //Here is an example of how to use WebClient class and HttpClient class in UWP

        var url  = string.Format(UrlTemplate, "CreateObject");
        var data = JsonConvert.SerializeObject(updatedObject, Formatting.Indented);

#if UNITY_EDITOR
        var webClient = new WebClient();
        webClient.Headers["content-type"] = "application/json";
        /* Always returns a byte[] array data as a response. */
        var response_data = webClient.UploadString(url, "POST", data);

        // Parse the returned data (if any) if needed.
        var responseString = response_data;

        Debug.LogWarning(responseString);
        return(JsonConvert.DeserializeObject <UnityPrimitive>(response_data));
#else
        var client  = new Windows.Web.Http.HttpClient();
        var content = new Windows.Web.Http.HttpStringContent(data, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
        Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(new Uri(url), content);

        UnityPrimitive result = null;
        if (response.IsSuccessStatusCode)
        {
            var stringres = await response.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject <UnityPrimitive>(stringres);
        }

        return(result);
#endif
    }
        async private Task UpdateSentimentValuesForNewNews(List <News> news)
        {
            try
            {
                var input = CreateJsonInput(news);
                var uri   = new Uri("https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment");

                using (var client = new HttpClient())
                {
                    using (var content = new Windows.Web.Http.HttpStringContent(input, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"))
                    {
                        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", AccountKey);
                        client.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json"));

                        var result = await client.PostAsync(uri, content);

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

                        MergeUpdatedSentimentsWithCacheValues(resStr);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error($"Cognitive service call failed: {e.Message}");
            }
        }
示例#4
0
        /// <summary>
        /// POST for all events sent to the Alexa Voice Service using the events path
        /// Refer ro : https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/docs/avs-http2-requests
        /// </summary>
        /// <returns></returns>
        public async Task CreatePOSTConnection()
        {
            Windows.Web.Http.HttpClient post = new Windows.Web.Http.HttpClient();
            post.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", Ini.access_token);
            post.DefaultRequestHeaders.Add("Keep-Alive", "true");

            var content = new Windows.Web.Http.HttpMultipartFormDataContent();

            string json          = "{\"event\":{\"header\":{\"namespace\":\"System\",\"name\":\"SynchronizeState\",\"messageId\":\"fakeMessageID\"},\"payload\":{}}}";
            var    stringContent = new Windows.Web.Http.HttpStringContent(json);

            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"metadata\"");

            content.Add(stringContent, "metadata");

            Debug.WriteLine("Confirm just before POST");
            var response = await(post.PostAsync(eventsURL, content));
        }
示例#5
0
        //downloads user-tags and returns list of SamTags
        public async Task <SamTagResponse> GetTags()
        {
            HttpClient client         = new HttpClient();
            Uri        domain         = new Uri(_serverUrl + "get_usertags/");
            JsonObject tagRequestJson = new JsonObject();

            tagRequestJson.SetNamedValue("userID", JsonValue.CreateNumberValue(_userId));
            Windows.Web.Http.HttpStringContent httpFrame = new Windows.Web.Http.HttpStringContent(tagRequestJson.Stringify());

            try
            {
                HttpResponseMessage response = await client.PostAsync(domain, httpFrame);

                SamServerResponse result = AnalyzeResponse(response);
                if (result.successfull)
                {
                    return(new SamTagResponse
                    {
                        successfull = true,
                        Tags = JsonConvert.DeserializeObject <List <SamTag> >(response.Content.ToString())
                    });
                }
                else
                {
                    //server error
                    return(new SamTagResponse {
                        successfull = false, ErrorMessage = result.ErrorMessage
                    });
                }
            }
            catch (Exception)
            {
                //connection error
                return(new SamTagResponse {
                    successfull = false, ErrorMessage = GenericConnectionFailedResponse.ErrorMessage
                });
            }
        }
示例#6
0
        //Post To Github
        private async void GitHubPost(string gh_content)
        {
            // Create an HttpClient instance
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = Windows.Web.Http.Headers.HttpCredentialsHeaderValue.Parse("token token#here");
            client.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("username"));
            client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.golden-comet-preview+json");
            
            if (!string.IsNullOrEmpty(gh_content))
            {
                Windows.Web.Http.HttpStringContent content = new Windows.Web.Http.HttpStringContent(gh_content);
                Debug.WriteLine(gh_content);
                
                Uri url = new Uri("https://api.github.com/repos/organizationname/reponame/import/issues"); 

                HttpResponseMessage response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();

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

            }

            else
            {
                Debug.WriteLine("content is empty");
                return;
            }

          
        }