【问题标题】:Windows.Web.Http.HttpClient in Windows Phone 8.1Windows Phone 8.1 中的 Windows.Web.Http.HttpClient
【发布时间】:2015-02-12 18:16:58
【问题描述】:

我正在编写一个 Windows Phone 8.1 应用程序 (WINRT)。我创建了一个登录页面,并希望将登录数据发布到服务器并获得响应。

感谢@Kai Brummund,他为我提供了以下方法,但它使用旧的 System.Net.Http;但我想使用强烈推荐的 Windows.Web.Http.HttpClient

使用新的命名空间,在这个方法中到处都是错误。我需要做出哪些改变?

 CancellationTokenSource cancellationToken;
        public async void ReadHeaders()
        {
            cancellationToken = new CancellationTokenSource();

            // Create the message
            string address = singletonInstance.APIServer + "MkhAdapter/rest/mkh/Login";
            var message = new HttpRequestMessage(HttpMethod.Post, new Uri(address));

            // Add the message body
            message.Content = new StringContent(
               LoginJsonData,
                System.Text.UTF8Encoding.UTF8, "application/json");

            ////filter/compress
            //HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();

            // Send
            var client = new HttpClient();
            var result = await client.SendAsync(message, cancellationToken.Token);

            result.EnsureSuccessStatusCode();

            // Get ids from result
            var finalresult = await result.Content.ReadAsStringAsync();
        } 

【问题讨论】:

  • 有什么错误?

标签: c# windows-runtime httpwebrequest windows-phone-8.1 httpwebresponse


【解决方案1】:

基本上你想做一个 Http Post 请求,对吧? 您可以只使用 WebClient:

        // Create the message
        var message = new HttpRequestMessage(HttpMethod.Post, new Uri(singletonInstance.APIServer + "MkhAdapter/rest/mkh/Login"));

        // Add the message body
        message.Content = new StringContent(
            "{'UserCategory': 'user','Email': User_EnteredUsername, 'Password':User_EnteredPassword}",
            System.Text.UTF8Encoding.UTF8, "application/json");

        // Send
        var client = new HttpClient();
        var result = await client.SendAsync(message, cancellationToken);

        result.EnsureSuccessStatusCode();

        // Get ids from result
        return (await result.Content.ReadAsStringAsync());

【讨论】:

  • 好吧 405 指出,您的 Http Endpoint 不支持请求类型 (GET)。正如您之前发送的 POST 请求一样,我建议您再次发送。这就是在示例中发布 POST 请求的原因。
  • 我使用了你的方法,它使用旧的 System.Net.Http;但我想使用高度推荐的 Windows.Web.Http.HttpClient
  • 取决于:Windows.Web.Http 仅在 Windows 上可用。 System.Net.Http 可以在 Android/Wpf 等上使用。两者都具有几乎相同的 Api thaugh。
猜你喜欢
  • 2023-04-03
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
相关资源
最近更新 更多