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

时间:2017-06-21 12:47:57

标签: c# json asp.net-mvc web-services rest

我想使用C#在POST请求中发送json数据。

我尝试了很多方法,但面临很多问题。我需要请求使用请求体作为来自字符串的原始json和来自json文件的json数据。

如何使用这两种数据表单发送请求。

Ex:对于json中的身份验证请求正文 - > {"Username":"myusername","Password":"pass"}

对于其他API请求体应从外部json文件中检索。

4 个答案:

答案 0 :(得分:35)

您可以使用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"));
}

enter image description here

当您需要HttpClient以上时,建议您只创建一个实例并重复使用它或使用新的HttpClientFactory

答案 1 :(得分:12)

您可以使用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();
}

答案 2 :(得分:4)

您可以使用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();

        }

答案 3 :(得分:2)

这适合我。

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}