Introduction
This is a small tip that would help you to understand how to POST XML input parameter to RESTful API and get the response back in C#.
Using the Code
I am explaining main functions that actually are calling RESTful API and passing the XML parameter, you can find the complete running Windows Application in the download section.
btnInvokeWebAPI_Click
button will load the XML file into XDocument
object from the path specified in txtXMLPath
textbox. You can also use XmlDocument
class if you want.
ExecutePOSTWebAPI
function will receive the RESTful API URL in resourceName
and XDcoument
object in classObj
parameters.
If your RESTful API requires SSL certificate but you want to bypass it for testing, you can add the following line of code:
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
httpContect
variable has input XML converted into string
with encoding type as UTF8 and content type as XML. PostAsync
method of HttpClient
object will post httpContent
, in our case the input XML to RESTful API and will store the result in response
variable.
The response
variable would have StreamContent
content type so we can use Content.ReadStringAsync()
method to get the result in Task<string>
format that later we are using to get the string and showing it in textarea txtResponse
control.
private void btnInvokeWebAPI_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(txtXMLPath.Text.Trim());
ExecutePOSTWebAPI(txtAPIAddress.Text.Trim(), doc);
}
public void ExecutePOSTWebAPI(string resourceName, object classObj)
{
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
try
{
var httpContent = new StringContent
(classObj.ToString(), Encoding.UTF8, "application/xml");
var response = client.PostAsync(resourceName, httpContent).Result;
var res = response.Content.ReadAsStringAsync();
switch (response.ReasonPhrase.ToLower())
{
case "ok":
txtResponse.Text = res.Result;
break;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.InnerException.Message);
}
}
}
History