How to post JSON to a server using C#?

后端 未结 13 1641
臣服心动
臣服心动 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条回答
  •  难免孤独
    2020-11-22 06:27

    The HttpClient type is a newer implementation than the WebClient and HttpWebRequest.

    You can simply use the following lines.

    string myJson = "{'Username': 'myusername','Password':'pass'}";
    using (var client = new HttpClient())
    {
        var response = await client.PostAsync(
            "http://yourUrl", 
             new StringContent(myJson, Encoding.UTF8, "application/json"));
    }
    

    When you need your HttpClient more than once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.

提交回复
热议问题