How to post non-standard XML with C# - c#

I have utilities that post standard XML, but am faced with interacting with a server that requires something I'm not familiar with.
The expected XML format is like this:
"xmldata=<txn><element_1>element_1_value</element_1><element_2>element_2_value</element_2></txn>"
When I post using my standard method:
byte[] data = Encoding.ASCII.GetBytes(XDocumentToString(xml));
var client = new WebClient();
client.Headers.Add("Content-Type", "text/xml");
byte[] result = client.UploadData(new Uri(url), "POST", data);
string resultString = Encoding.ASCII.GetString(result);
return XDocument.Parse(resultString);
I get an error message about the XML not being formatted correctly.
When I use some stuff I've found:
var request = _requestFactory.CreateCreditCardSaleRequest(xmlStringFromAbove);
WebRequest webRequest = WebRequest.Create("https://domain.com/process_some_xml.do");
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(request);
// Set the ContentType property of the WebRequest.
webRequest.ContentType = "text/xml; encoding='utf-8'";
// Set the ContentLength property of the WebRequest.
webRequest.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = webRequest.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
// dataStream.Close();
// Get the response.
WebResponse response = webRequest.GetResponse();
// Display the status.
var httpWebResponse = (HttpWebResponse) response;
Console.WriteLine(httpWebResponse.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
the response seems to indicate success, but no response content as expected.
I suspect it has something to do with the "xmldata=" at the beginning of the request, but cannot be sure.
Any suggestions?

Judging from the xmldata=, it sounds like the API wants the data sent as form-urlencoded. I suggest trying this:
string dataStr = "xmldata=" + HttpUtility.UrlEncode(XDocumentToString(xml));
byte[] data = Encoding.ASCII.GetBytes(dataStr);
and this:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

Related

How to post a request to Java servlet from .net

How to post the following data to servlet url:
Data:
enc_request=63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550&access_code=8JXENNSSBEZCU8KQ&command=confirmOrder&request_type=XML&response_type=XML&version=1.1
Url:
"https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
I tried https://social.msdn.microsoft.com/Forums/vstudio/en-US/df76fbfa-2931-4c9f-8671-785307243f62/post-request-to-a-java-servlet-and-process-httpresponse-using-net?forum=wcf . But I'm getting the error: C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
Below is my code:
StringBuilder sbQueryString = new StringBuilder();
CCACrypto ccaCrypto = new CCACrypto();
string workingKey = "14A246E9D4341159638AC8EB776F3BE6";
//put in the 32bit alpha numeric key in the quotes provided here
sbQueryString.Append("enc_request=");
sbQueryString.Append(ccaCrypto.Encrypt(GenerateOrderXml(appointmentId), workingKey));
sbQueryString.Append("&");
sbQueryString.Append("access_code=");
sbQueryString.Append("AVQJ68DL46BW00JQWB");
sbQueryString.Append("&");
sbQueryString.Append("Command=");
sbQueryString.Append("cancelOrder");
sbQueryString.Append("&");
sbQueryString.Append("request_type=XML&response_type=XML");
sbQueryString.Append("&");
sbQueryString.Append("version=1.1");
//Response.Redirect("../ccAvenue/ccavAPIHandler.aspx?" + sbQueryString.ToString(), false);
//string url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
string url = "https://180.179.175.17/apis/servlet/DoWebTrans";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = sbQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.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();
You can try simplifying your code by using a WebClient:
using (var client = new WebClient())
{
var data = new NameValueCollection
{
{ "enc_request", "63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550" },
{ "access_code", "8JXENNSSBEZCU8KQ" },
{ "command", "confirmOrder" },
{ "request_type", "XML" },
{ "response_type", "XML" },
{ "version", "1.1" },
};
var url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
byte[] result = client.UploadValues(url, data);
}

(400) Bad Request, can't get response (Custom minecraft launcher)

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

How make a post to URL and get the response

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

why is my String throw error?

I want to target this string type "application/json" for urban airship api. Can you guys help me whats wrong with my string and structure?
string postData = "{"audience":"all","device_types":["android"],"notification":{"alert":"This is a broadcast."}}";
I did tried adding back slash "\" example below:
string postData = "{\"audience\":\"all\",\"device_types\":[\"android\"],\"notification\":{\"alert\":\"This is a broadcast.\"}}";
Below are my full code:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{'audience':'all','device_types':'['android']','notification': {'alert':'This is a broadcast.'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "Zx5EPSG7Qhu-BvYtz0laTg";
string password = "sIaj2CjASlm27pimHqOfhA";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.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();
I got below error:
400 Bad Request – The request body was invalid, either due to malformed JSON or a data validation error. See the response body for more detail.
This should work:
{
"audience" : "all",
"device_types" : ["android"],
"notification" : {
"alert" : "This is a broadcast."
}
}
You have small type in the first value, an additional ' sign after "all":
{
"audience": "all"',
"device_types": [
"android"
],
"notification": {
"alert": "This is a broadcast."
}
}
In future, you can use online validators for such cases, like JSONLint.

c# WebRequest Wont Post the whole length of data

I am currently having a problem.
I am trying to post my data to a PHP document but it does not get the whole value.
Somewhere in the middle it stops posting.
Does anyone know where the problem is located?
The bytearray is 7401 long. That cant be to long rigth?
My code is below:
public string RecieveData(string url, string postData = "")
{
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
NetworkCredential nc = new NetworkCredential("user", "pass");
Stream dataStream;
if (postData != "")
{
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
request.Credentials = nc;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(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);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
/*
}
catch (Exception)
{
MessageBox.Show("Er is iets fout gegaan met verbinden");
return "";
}
*/
}
7401 is not too long.
My guess is that the data you are posting are not fully URL-encoded, e.g. one of the characters in the byte array causes the PhP parser to stop. Make sure you are looking at the raw data (e.g. using Wireshark).

Categories