Domanda

I am writing a service in C# .NET that takes some data, generates an XML string, and posts it to a webservice.

I have that working properly, but now I want to base64encode the XML string on the C# end and decode it in PHP on the webservice side.

Something is going wrong, because the decoding is not working as expected on the PHP side

On the PHP side I just do

$xml = trim(base64_decode($_POST['xmlpost']));

Which works fine from webservice to webservice.

Here is the C# code:

string xml = ###XMLHERE###;
WebRequest request = (HttpWebRequest)WebRequest.Create(liveURL);

//base 64 encode
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(xml);
string byteArrayEncoded = System.Convert.ToBase64String(plainTextBytes, 0, plainTextBytes.Length);

byte[] byteArray = Encoding.UTF8.GetBytes("xmlpost=" + byteArrayEncoded + "&test=1");

//send request
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.Method = "POST";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

I know the XML format is correct because it works fine without encoding. What am I doing wrong?

Side note: after I fix this I am also trying to ensure that single quotes, double quotes and ampersands can be in the XML node text, if anyone can also help me with that.

enter image description here

È stato utile?

Soluzione

The base64 encoding uses characters like +, / and = that must be escaped in the URL encoded form data. Something like this should yield better results for you.

string byteArrayEncoded = System.Convert.ToBase64String(plainTextBytes, 0, plainTextBytes.Length);
string byteArrayUrlEncoded = System.Web.HttpUtility.UrlEncode(byteArrayEncoded);
byte[] byteArray = Encoding.UTF8.GetBytes("xmlpost=" + byteArrayUrlEncoded + "&test=1");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top