在UWP(W10)中使用HttpClient发出POST请求 [英] Make a POST request with HttpClient in UWP(W10)

查看:253
本文介绍了在UWP(W10)中使用HttpClient发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用通用Windows Plataform制作应用程序,我想问一下如何使用httpclient将(​​id = 1)之类的数据发布到服务器. 我知道互联网上有一些教程,但是其中许多教程是针对Windows 8.1的,不能在10中使用.

I'm using the Universal Windows Plataform for making a App and I want to ask how to post data like (id=1) to the server with httpclient. I know that there is some tutorials on internet, but many of them are for Windows 8.1 and don't work in 10.

推荐答案

如果要在UWP中处理HTTP请求,则需要一个Web服务来支持它.如果您在解决方案中创建一个Web API项目,则可以使用控制器内部的操作来处理POST请求.

If you want to handle HTTP request in UWP, you need a webservice to support it. If you make a web API project in your solution, then you can use the actions inside controllers to handle the POST request.

有关Web API的更多信息:

More reading about web API: click here

首先,您需要从NuGet安装Web API .net客户端,以处理来自Web API的HTTP请求.

First you need to install the web API .net Client from NuGet to handle HTTP request from web API.

在您的UWP项目中,您可以使用以下方法创建数据传输类:

in your UWP project, you can then make a Data transfer class with the following method:

const string ServerUrl = ""; //specify your server url

 public void ClientHeaderInfo(HttpClient client)
 {
        client.BaseAddress = new Uri(ServerUrl);
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 }

public virtual async Task Post(int id,string url)
    {
        HttpClientHandler handler = new HttpClientHandler { UseDefaultCredentials = true };
        using (var client = new HttpClient(handler))
        {
            ClientHeaderInfo(client);
            try
            {
                await client.PostAsJsonAsync(url, id);

            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }

    }

现在,您可以在任何需要的地方调用Post方法,并将URL路由到Web API中所需的控制器,以及您需要发布的ID.

Now you can call the Post method where ever you need it, with the url routing to the desired controller in the web API, and the id you need to POST.

这篇关于在UWP(W10)中使用HttpClient发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆