Post XML over HTTP and capture the response – C#
Recently we got a requirement to post the data from ‘CRM Plug-in’ to an external API and capture response.
External API was built as XML over HTTP (i.e., Its not a SOAP based and no WSDL).
In this approach we post the Request XML to a URL and in return we will get the Response.
Refer below test client with Request and Response XML’s.
Request XML
Response XML
C# Code:
- In XML over HTTP we will post the Request XML to a URL and get the Response.
- So the below C# function accepts URL and RequestXML as Parameters and return the Response.
public static XmlDocument SubmitXmlRequest(string apiUrl, string reqXml){
XmlDocument xmlResponse = null;
HttpWebResponse httpWebResponse = null;
Stream requestStream = null;
Stream responseStream = null;// Create HttpWebRequest for the API URL.
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);try{
// Set HttpWebRequest properties
var bytes = System.Text.Encoding.ASCII.GetBytes(reqXml);
httpWebRequest.Method = “POST”;
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = “text/xml; encoding=’utf-8′”;//Get Stream object
requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();// Post the Request.
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();// If the submission is success, Status Code would be OK
if (httpWebResponse.StatusCode == HttpStatusCode.OK){
// Read response
responseStream = httpWebResponse.GetResponseStream();if (responseStream != null){
var objXmlReader = new XmlTextReader(responseStream);// Convert Response stream to XML
var xmldoc = new XmlDocument();
xmldoc.Load(objXmlReader);
xmlResponse = xmldoc;
objXmlReader.Close();
}
}// Close Response
httpWebResponse.Close();
}
catch (WebException webException)
{
throw new Exception(webException.Message);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
// Release connections
if (requestStream != null){
requestStream.Close();
}if (responseStream != null){
responseStream.Close();
}if (httpWebResponse != null){
httpWebResponse.Close();
}
}// Return API Response
return xmlResponse;
}
Capture and Read the Response
XmlDocument response = SubmitXmlRequest(uri, xmlString);
Console.WriteLine(“Inner Text – ” + response.InnerText);
Console.WriteLine(“Inner XML – ” + response.InnerXml);
🙂
I m getting error