How to post JSON to a server using C#?
OR
Calling REST API in C# (Read JSON Data)
Sample Code C#:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
//*************************************************************************//
var httpWebRequest = (HttpWebRequest)WebRequest.Create("YOU API URL");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("APIKey", "111111111111111111");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(new
{
appId = "XXXX",
vehicleRequestChoice = new
{
plateDetails = new
{
plateCategory = "Private",
plateCode = "T",
plateNo = "11111"
}
}
}
);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
var result = streamReader.ReadToEnd();
var testobj = JsonConvert.DeserializeObject(result);
return testobj;
}
}
//***************** END ******************//
No comments:
Post a Comment