如何使用C#发送POST请求中的json数据

这个问题在这里已经有了答案:

  • 如何发布JSON到服务器? 11个答案

  • 您可以使用HttpClient而不是WebClientHttpWebRequest 。 这是一个更新的实现。

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

    在这里输入图像描述


    你可以用HttpWebRequest来做到这一点:

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "pass"
                });
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
    

    你可以使用HttpClientRestSharp ,因为我不知道你的代码是什么,这里是一个使用httpclient的例子:

    using (var client = new HttpClient())
            {
                //This would be the like http://www.uber.com
                client.BaseAddress = new Uri("Base Address/URL Address");
                //serialize your json using newtonsoft json serializer then add it to the StringContent
                var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 
                //method address would be like api/callUber:SomePort for example
                var result = await client.PostAsync("Method Address", content);
                string resultContent = await result.Content.ReadAsStringAsync();
    
            }
    
    链接地址: http://www.djcxy.com/p/45863.html

    上一篇: How to send json data in POST request using C#

    下一篇: How to send few parameters via POST method?