Eugene
Eugene

Reputation: 231

POST Request UWP

I writing UWP app.

I need to send POST request with json to server

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

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

Thank's for help.

Upvotes: 1

Views: 4297

Answers (2)

Allen Rufolo
Allen Rufolo

Reputation: 1202

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

Upvotes: 4

toadflakz
toadflakz

Reputation: 7934

You should be using httpClient.PostAsync().

Upvotes: 1

Related Questions