24

I want to send json data in POST request using C#.

I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.

How can i send request using these two data forms.

Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}

For other APIs request body should retrieved from external json file.

0

3 Answers 3

22

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using 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();   
}
0
20

You can do it with 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();
}
7
  • This is showing error : An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The underlying connection was closed: An unexpected error occurred on a send when it comes to GetResponse(). I have only added one extra header parameter - API Key
    – Rocky
    Jun 21, 2017 at 14:52
  • Can you try with httpWebRequest.KeepAlive = false; ? I've updated the answer.
    – kkakkurt
    Jun 21, 2017 at 14:57
  • No , still same error in same line!
    – Rocky
    Jun 21, 2017 at 15:04
  • 1
    Security protocol can cause this error, you can also try with ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;. Updated answer.
    – kkakkurt
    Jun 21, 2017 at 15:08
  • 3
    As I understand it you don't need the Flush and Close on the streamwriter if it's created with using.
    – GMK
    Nov 9, 2018 at 21:20
5

This works for me.

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();
}
1
  • This is also showing the same error as above answer : An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The underlying connection was closed: An unexpected error occurred on a send when it comes to GetResponse(). I have only added one extra header parameter - API Key
    – Rocky
    Jun 21, 2017 at 15:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.