I have a .NET project which posts data to foreign web server in the form of a SOAP object via HTTP POST. This is done using a HttpWebRequest object. I get a response from the web server, which I am capturing with an HttpWebResponse object. This response object is also XML surrounded by a SOAP envelope.
The problem is, when I take the response and output it to the screen with ToString it apparently nukes all of the tags and just combines it all into a single string.
How can I output the returned XML from the web server without removing all the XML formatting/tags?
Here is the code I am using:
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.Headers.Add("SOAPAction", "Some Headers");
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
sResponse = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString();
You could format an xml to pretty-printed form as follows:
string xml = "<?xml version='1.0' encoding='UTF-8'?><foo><bar></bar></foo>";
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
MemoryStream memStream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(memStream, settings))
{
document.Save(writer);
}
memStream.Flush();
string formattedXml = Encoding.UTF8.GetString(memStream.ToArray());
// strip UTF-8 BOM if required. Good for display purposes, can leave as such
// for normal processing.
string preAmble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (formattedXml.StartsWith(preAmble))
{
formattedXml = formattedXml.Remove(0, preAmble.Length);
Console.WriteLine(formattedXml);
}
Outputs
<?xml version="1.0" encoding="utf-8"?>
<foo>
<bar></bar>
</foo>
Hope this helps.
Cheers,
Anash
Related
I keep getting the infamous 'Root element is missing' error when Posting XML data. It sometimes works, but most times throws the error.
C# Code:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return "";
}
XML Data:
<Person>
<idPeople>0</idPeople>
<AccountNumber>TEST02H</AccountNumber>
<cFirstName>TEST 2</cFirstName>
<cLastName>TEST 2</cLastName>
<cTelWork/>
<cTelMobile>0713473835</cTelMobile>
<cEmail>myemail#mydomain.com</cEmail>
<ubPPLIsActive>true</ubPPLIsActive>
<ubPPLSMSOptIn>true</ubPPLSMSOptIn>
<udPPLSMSOptInActivateDate>30/05/2017</udPPLSMSOptInActivateDate>
<ulPPLAccessType>Administrator</ulPPLAccessType>
<ubPPLNewsletterSignUp>true</ubPPLNewsletterSignUp>
<ubPPLIncludeBuyerEmails>true</ubPPLIncludeBuyerEmails>
</Person>
The issue for me was in 2 places.
The application I am posting to had an error, which I resolved. I found this error by pasting the destination URL into my browser to see what happens.
I needed to System.Web.HttpUtility.UrlEncode the XML.
I used this method for posting in the end.
WebClient client = new WebClient();
string xmlResult = client.DownloadString(_workContext.AccountingWebServiceLink + "?action=updatesecondary&xml=" + System.Web.HttpUtility.UrlEncode(strXML));
Here I am getting proper result but my problem is very slow response getting from the server.
Please suggest any other fastest method to call web service. Help appreciated.
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><availabilityRequest cancelpolicy = \"Y\">with more condition</availabilityRequest>
String responseStr = postXMLData("http://service-url", xml);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseStr);
public String postXMLData(string destinationUrl, string requestXml)
{
string responseStr = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
responseStr = new StreamReader(responseStream).ReadToEnd().Trim();
}
return responseStr;
}
In my web project, I am using http request and response for access https payment site. But when I call getresponse() function, it return "Precondition failed (412)" error.
HttpWebRequest paymentRequest = (HttpWebRequest)WebRequest.Create("https://xxxxxx/authorize");
Uri uri = new Uri("https://xxxxxx/authorize");
NetworkCredential netCredential = new NetworkCredential("XXXXXXXXX", "XXXXXXXXX");
paymentRequest.Credentials = netCredential.GetCredential(uri, "Basic");
paymentRequest.PreAuthenticate = true;
byte[] Data = System.Text.Encoding.ASCII.GetBytes(sXMLTemplate);
paymentRequest.Method = "POST";
paymentRequest.Headers.Add("MIME-Version", "1.0");
paymentRequest.Headers.Add("Request-number", "1");
paymentRequest.Headers.Add("Document-type", "Request");
paymentRequest.Headers.Add("Content-transfer-encoding", "application/xml");
paymentRequest.ContentType = "application/xml";
paymentRequest.ContentLength = Data.Length;
paymentRequest.KeepAlive = true;
Stream streamWriter = paymentRequest.GetRequestStream();
streamWriter.Write(Data, 0, Data.Length);
streamWriter.Close();
HttpWebResponse paymentResponse = (HttpWebResponse)paymentRequest.GetResponse();
Stream responseStream = paymentResponse.GetResponseStream();
reader = new XmlTextReader(responseStream);
How to fix this error?
Please check if XML data you are POSTing validates successfully and there is no missing XML elements if XML schema is enforced
Have a look at the valid content-transfer-encodings.
BASE64
8BIT
7BIT
BINARY
QUOTED-PRINTABLE
application/something is for Content-Type, not encoding.
For more info, look at the specs here:
http://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html
What I do Think you're after is this:
paymentRequest.Headers.Add("Content-type", "application/xml");
or simply:
paymentRequest.ContentType = "application/xml";
I am trying to send an XML file to a Webservice.
Here's the code that loads the XML and saves it to the stream:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(mesServiceURL);
request.Method = "POST";
request.ContentType = "application/xml";
Stream request_stream = request.GetRequestStream();
xmlDoc.Save(request_stream);
request_stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream r_stream = response.GetResponseStream();
StreamReader response_stream = new
StreamReader(r_stream, System.Text.Encoding.GetEncoding("utf-8"));
string sOutput = response_stream.ReadToEnd();
The request_stream object's length property has this :
'request_stream.Length' threw an exception of type 'System.NotSupportedException'
On disk the XML is 3 kb so it's not huge.
So, how do I solve this?
Thanks in advance.
I have been doing some Google searches and only getting partial successful on this topic. I was wondering if someone could suggest an example of doing an HTTP POST using C# to send XML to HTTP service.
I have a asmx web service that extracts data from database and I save that data to XML document. Now I have to send that XML document using SOAP protocol to HTTP service.
I have this part of code for connectig to service
WebRequest myReq = WebRequest.Create("https://WEB_URL");
System.Net.ServicePointManager.CertificatePolicy = new CertificatePolicyClass();
string username = "SOMETHING";
string password = "ELSE";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://WEB_URL"), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
So does anybody have a code to send XML document to http service, this part I don't know how to write, I don't know am I on the write trace, I belive it has to go somethig like this
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
So plese can somebody help me! THANKS!
Here is something I get, hope it's useful to you:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://WEB_URL");
myReq.Method = "POST";
myReq.ContentType = "text/xml";
myReq.Timeout = 30000;
myReq.Headers.Add("SOAPAction", ":\"#save\"");
byte[] PostData = Encoding.UTF8.GetBytes(xmlDocument);
myReq.ContentLength = PostData.Length;
using (Stream requestStream = myReq.GetRequestStream())
{
requestStream.Write(PostData, 0, PostData.Length);
}
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
string soap =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<Register xmlns=""http://tempuri.org/"">
<id>123</id>
<data1>string</data1>
</Register>
</soap:Body>
</soap:Envelope>";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");
req.Headers.Add("SOAPAction"http://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
}
}
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();