POST请求UWP

时间:2016-11-08 14:20:53

标签: c# json visual-studio uwp

我正在编写UWP应用程序。

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

以下是我下载JSON和写入值的代码:

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请求?

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

以下是我在UWP应用程序中使用的Post请求示例。

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
    }
}

答案 1 :(得分:1)

您应该使用httpClient.PostAsync()