Windows Phone 8.1发布请求

时间:2015-07-09 06:12:13

标签: c# azure windows-phone-8.1 twilio

我正在开发Windows Phone 8.1应用程序。 我正在利用Twilio一起发送带有Azure服务的文本消息。 事实是,我必须向URL发布请求。当我使用Fiddler提出请求时,一切都很棒!但是,我不知道如何使用C#重现相同的内容。我尝试使用HTTP客户端,但不知道如何让它运行良好。 有人可以帮助我吗? 提前感谢你。

using SDKTemplate;
using Windows.UI.Xaml.Controls;using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;

namespace SDKSample.HttpClientSample
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Scenario6 : Page, IDisposable
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        private HttpClient httpClient;
        private CancellationTokenSource cts;

        public Scenario6()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Helpers.CreateHttpClient(ref httpClient);
            cts = new CancellationTokenSource();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // If the navigation is external to the app do not clean up.
            // This can occur on Phone when suspending the app.
            if (e.NavigationMode == NavigationMode.Forward && e.Uri == null)
            {
                return;
            }

            Dispose();
        }

        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            Uri resourceAddress;

            // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
            // valid, absolute URI, we'll notify the user about the incorrect input.
            if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
            rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

            try
            {
                HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
                form.Add(new HttpStringContent(RequestBodyField.Text), "data");

                HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form).AsTask(cts.Token);

                await Helpers.DisplayTextResultAsync(response, OutputField, cts.Token);

                rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
            }
            finally
            {
                Helpers.ScenarioCompleted(StartButton, CancelButton);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
            cts.Dispose();

            // Re-create the CancellationTokenSource.
            cts = new CancellationTokenSource();
        }

        public void Dispose()
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
                httpClient = null;
            }

            if (cts != null)
            {
                cts.Dispose();
                cts = null;
            }
        }
    }
}

好吧, 我试过以下的。它似乎是在json中发送请求但没有正文。如何使用以下代码以JSON格式发送请求?

using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
       { "thing1", "hello" },
       { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
}

这里我的新代码无法正常工作(获取错误无法转换,无法从&#39; windows.web.http.http stringcontent&#39;转换为&#39; system.net.http.httpcontent&#39; on line System.Net.Http.HttpResponseMessage response = await client.PostAsync(&#34; http://twilionotifs.azure-mobile.net/api/notificationqueue&#34;,stringContent);):

private async void Button_Click(object sender, RoutedEventArgs e)
        {

                  HttpStringContent stringContent = new HttpStringContent("{ \"firstName\": \"John\" }",
    Windows.Storage.Streams.UnicodeEncoding.Utf8,
    "application/json");

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response = await client.PostAsync("http://twilionotifs.azure-mobile.net/api/notificationqueue", stringContent);
            }
        }

0 个答案:

没有答案