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.
You should put the JSON into the value of a normal POST variable: request. send('data=' + encodeURIComponent(JSON. stringify(objJSON));
To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.
POST requests In Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.
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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With