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.
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;
}
I try to post an XML file to the url and get the response back. I have this code to post. I am not really sure how to check if it is posting correctly and how to get the response.
WebRequest req = null;
WebResponse rsp = null;
// try
// {
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
I think I should have response in rsp but I am not seeing anything usufull on it.
Please try following.
WebRequest req = null;
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Write the XML text into the stream
byte[] byteArray = Encoding.UTF8.GetBytes(this.GetTextFromXMLFile(fileName));
// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = req.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = req.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
try
req.ContentType = "application/xml";
my url is :
http://localhost:8983/solr/db/select/?q=searchtext&version=2.2&start=0&rows=10&indent=on
How can i get response (xml data) from this url in asp.net. my result search is :
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
String a = response.ResponseUri.ToString();
But, I cant get content of xml data.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
String a = readStream.ReadToEnd();
ResponseUri is just the URL for the response. You need to use GetResponseStream().
You should probably be using the XmlDocument class.
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx
Your code would look something like this:
XmlDocument doc = new XmlDocument();
doc.Load(response.GetResponseStream());
string root = doc.DocumentElement.OuterXml;
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