HTTP post XML data in C# (Error in request.GetRequestStream()) - c#

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;
}

Related

C# Post-Request Status 400 Bad Request

I am currently working on a C# Programm that is supposed to get Data from a REST API that I host.
The API requires a token for authentication which is returned from a POST request.
When I try to do the POST with C# I get a bad request (Status 400) but the GET request works fine. Now, My question is what I did wrong or what might be the cause for that error. When doing the request with postman both work perfectly.
The POST function:
void POST(string url, string jsonContent) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
Console.WriteLine(response);
}
} catch (WebException ex) {
Console.WriteLine(ex);
}
}
The GET function:
string GET(string url) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}

Post XML to MVC Controller C#

I'm trying to post XML from www.domain1.com a controller in www.domain2.com.
Here is my code:
www.domain2.com
[HttpPost]
public ActionResult FetchProductsXML()
{
Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
var products = _productService.SearchProducts(showHidden: false);
var xml = _exportManager.ExportProductsToXml(products);
return this.Content(xml, "text/xml");
}
Then in www.domain1.com I am posting as follows..
private string getProductLIstXML()
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = "<testXml>test</testXml>";
try
{
byte[] data = encoding.GetBytes(SampleXml);
string url = "http://www.domain2.com/products-xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(SampleXml);
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 null;
}
catch (WebException webex)
{
return webex.ToString();
}
}
My Custom Route in RouteProvider class
routes.MapLocalizedRoute("FetchProductsXML",
"products-xml",
new { controller = "Product", action = "FetchProductsXML" },
new[] { "Nop.Web.Controllers" });
The error I get is
System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.GetResponse()
I've followed what the examples from the following SOQ's
How to POST XML into MVC Controller? (instead of key/value)
HTTP post XML data in C#
After a long night, I realized I had the method in the incorrect class :(
All fixed now.

Post XML "Root Element Is Missing"

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));

Calling web service with XML post method and getting response in XML format which is very slow response

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;
}

SOAP API in salesforce for login

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

Categories