I'm trying to get a response from a URL which takes an Xml input and returns an Xml output.
And there is this case when this Url returns Bad Request 400, in this case in code I'll get an exception and I can't view the Xml, but if I tried the same input in postman I'll get the Xml output.
In case of the exception I can catch this exception by using WebException, but here in the end when I read the response using reader.ReadToEnd() I'll get a JSON not the Xml output that I got from postman
Postman output example:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<RESPONSE MODE="DIRECT" TYPE="PINPRINTING">
<RESULTMESSAGE>User not allowed to process</RESULTMESSAGE>
</RESPONSE>
and this is my code:
public void GetResponse()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURL);
request.Accept = "application/xml";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(requestXmlDoc.InnerXml);
request.Method = "POST";
request.ContentType = "text/xml;charset=utf-8";
request.ContentLength = requestInFormOfBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
string receivedResponse = respStream.ReadToEnd();
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data, ASCIIEncoding.ASCII))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
}
the returned JSON is something like this:
{
"status": 400,
"statusDesc": "Invalid input"
}