C#

HttpClient

DBASeoul 2022. 12. 22. 14:37
using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 
using Windows.Storage.Streams; 
using Windows.Web.Http; 
private async Task TryPostJsonAsync() 
{ 
    try 
    { 
        // Construct the HttpClient and Uri. This endpoint is for test purposes only. 
        HttpClient httpClient = new HttpClient(); 
        Uri uri = new Uri("https://www.contoso.com/post"); 
        // Construct the JSON to post. 
        HttpStringContent content = new HttpStringContent( 
            "{ \"firstName\": \"Eliot\" }", 
            UnicodeEncoding.Utf8, 
            "application/json"); 
        // Post the JSON and wait for a response. 
        HttpResponseMessage httpResponseMessage = await httpClient.PostAsync( 
            uri, 
            content); 
        // Make sure the post succeeded, and write out the response. 
        httpResponseMessage.EnsureSuccessStatusCode(); 
        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync(); 
        Debug.WriteLine(httpResponseBody); 
    } 
    catch (Exception ex) 
    { 
        // Write out any exceptions. 
        Debug.WriteLine(ex); 
    } 
}