How to post JSON to a server using C#?

后端 未结 13 1642
臣服心动
臣服心动 2020-11-22 05:55

Here\'s the code I\'m using:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.Protoco         


        
13条回答
  •  -上瘾入骨i
    2020-11-22 06:25

    I find this to be the friendliest and most concise way to post an read JSON data:

    var url = @"http://www.myapi.com/";
    var request = new Request { Greeting = "Hello world!" };
    var json = JsonSerializer.Serialize(request);
    using (WebClient client = new WebClient())
    {
        var jsonResponse = client.UploadString(url, json);
        var response = JsonSerializer.Deserialize(jsonResponse);
    }
    

    I'm using Microsoft's System.Text.Json for serializing and deserializing JSON. See NuGet.

提交回复
热议问题