POST 请求 UWP [英] POST Request UWP

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

问题描述

我正在编写 UWP 应用.

I writing UWP app.

我需要将带有 json 的 POST 请求发送到服务器

I need to send POST request with json to server

这是我下载 JSON 并写入值的代码:

Here is my code for downloading JSON and writing to value:

public async void AllOrders_down()
    {


        string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";

        var json = await FetchAsync(url);


        List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);

        OrdersList = new List<RootObject>(rootObjectData);


    }
    public async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }

我需要如何将带有此 json 的 POST 请求发送到服务器?

How I need to send POST request with this json to server?

感谢您的帮助.

推荐答案

这是我在 UWP 应用程序中使用的示例 Post 请求.

Here is an example Post request that I have used in a UWP application.

using (HttpClient httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri(@"http://test.com/");
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

    string endpoint = @"/api/testendpoint";

    try
    {
        HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json");
        HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);

        if (response.IsSuccessStatusCode)
        {
            string jsonResponse = await response.Content.ReadAsStringAsync();
            //do something with json response here
        }
    }
    catch (Exception)
    {
        //Could not connect to server
        //Use more specific exception handling, this is just an example
    }
}

这篇关于POST 请求 UWP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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