How to post JSON to a server using C#?

后端 未结 13 1643
臣服心动
臣服心动 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:04

    Further to Sean's post, it isn't necessary to nest the using statements. By using the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call the Flush() and Close() methods:

    var request = (HttpWebRequest)WebRequest.Create("http://url");
    request.ContentType = "application/json";
    request.Method = "POST";
    
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
                    {
                        user = "Foo",
                        password = "Baz"
                    });
    
        streamWriter.Write(json);
    }
    
    var response = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
            var result = streamReader.ReadToEnd();
    }
    

提交回复
热议问题