首页 > 代码库 > C# ContentType: "application/json" 请求方式传json参数问题

C# ContentType: "application/json" 请求方式传json参数问题

处理Http请求时遇到的ContentType为application/json方式,记录下这种Post请求方式下如何传json参数:

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

 

C# ContentType: "application/json" 请求方式传json参数问题