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.

Rocky
  • 857
  • 2
  • 8
  • 15

3 Answers3

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();   
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Masoud Andalibi
  • 3,168
  • 5
  • 18
  • 44
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();
}
kkakkurt
  • 2,790
  • 1
  • 30
  • 33
  • 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 '17 at 14:52
  • Can you try with _httpWebRequest.KeepAlive = false;_ ? I've updated the answer. – kkakkurt Jun 21 '17 at 14:57
  • No , still same error in same line! – Rocky Jun 21 '17 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 '17 at 15:08
  • Thanks ! This resolved , there was issues with this SSL/TLS. – Rocky Jun 21 '17 at 15:20
  • How can I send json file content to this POST request ? – Rocky Jun 21 '17 at 15:20
  • 3
    As I understand it you don't need the Flush and Close on the streamwriter if it's created with using. – GMK Nov 09 '18 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();
}
Rohan Das
  • 79
  • 5
  • 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 '17 at 15:10