POST Request UWP

本文关键字:UWP Request POST | 更新日期: 2023-09-27 18:16:53

我在写UWP app

我需要用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请求到服务器?

谢谢你的帮助

POST Request UWP

下面是我在一个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
    }
}

您应该使用httpClient.PostAsync()