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));
Related
I need to Post the XML data to a URL.But I am facing some Error in the (Stream requestStream = request.GetRequestStream()) Line
Errror Image .
I have saved the xml in the file and provided the path for that . I think there is Issue while passing XML Data but when I try to use the same XML in the POSTMan using POSTmethod.I can able to get the response Data.
This is the reference link HTTP post XML data in C#
And here is my code
static void Main(string[] args)
{
string url = "*****************";
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(#"Path of the xml file");
var sw = new StringWriter();
Xdoc.Save(sw);
string result = sw.ToString();
string response = **********.postXMLData(url, result);
Console.WriteLine(response);
Console.ReadLine();
}
public static 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";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
i am trying to implement my code as per these requirement. That is saying The response to this POST will include a header named LOCATION, which is a URL with parameters indicating where to upload the file via a second POST.. For request i have did below code but i stuck at point where i need to get LOCATION from header. For request i did below code and i want to get LOCATION from Header of response.
string responseStr = "";
HttpStatusCode statusCode;
WebRequest request = WebRequest.Create(URL);
//request.Credentials = new NetworkCredential(bigApiUserID, BigApiKey);
request.Method = "POST";
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(stringOrder);
request.Headers.Add("Authentication", token);
request.ContentType = "application/json";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode;
response.Headers
if (Convert.ToString(response.StatusCode) == "OK")
{
Stream responseStream = response.GetResponseStream();
responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
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 wants to get session id from salesforces using soap API for login. Below is my code for request but i am getting salesforce login page as html response.
Any thoughts ?
public static string Authentication()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SalesForce_authenticationAPI);
request.ContentType = "text/xml; charset=UTF-8";
request.Headers.Add("SOAPAction", #"\");
request.Method = "POST";
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(CreateSoapEnvelope().InnerXml);
request.ContentLength = bytes.Length;
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 only sessionId
return responseStr;
}
return null;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/' xmlns:x='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:partner.soap.sforce.com'><s:Body><login><username>xyz#account.com</username><password>*********</password></login></s:Body></s:Envelope>");
return soapEnvelop;
}
Rather than doing the SOAP stuff by hand, check out the Force.com-Toolkit-for-NET.
I don't have a .Net sample but here is a Scala example that uses the Salesforce SOAP API to login: https://github.com/jamesward/force-login
I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data