Reputation: 191
Ok, so the problem is I'm trying to send a byte array via HTTP encoded as base64. While the string I receive on the other end is the same size as the original string, the strings themselves are not identical, hence I can't decode the string back to the original byte array.
Also, I've done conversion to/from base64 on the client side before sending the string and everything works fine. It's after it gets sent that the problem occurs.
Is there anything I'm missing? Any particular formatting type? I've tried using EscapeData() but the string is too large.
Thank you in advance
edit: code
System.Net.WebRequest rq = System.Net.WebRequest.Create("http://localhost:53399/TestSite/Default.aspx");
rq.Method = "POST";
rq.ContentType = "application/x-www-form-urlencoded";
string request = string.Empty;
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\\temp.png"));
request += "image=" + image;
int length = image.Length;
byte[] array = new UTF8Encoding().GetBytes(request);
rq.ContentLength = request.Length;
System.IO.Stream str = rq.GetRequestStream();
str.Write(array, 0, array.Length);
System.Net.WebResponse rs = rq.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream());
string response = reader.ReadToEnd();
reader.Close();
str.Close();
System.IO.File.WriteAllText("c:\\temp\\response.txt", response);
Upvotes: 2
Views: 4577
Reputation: 31528
The second line below is the problem.
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png"));
request += "image=" + image;
If you look at Base 64 index table, the last two characters (+ and /) are NOT URL safe. So, when you append it to request, you MUST URL Encode the image.
I am not a .net guy, but the second line should be written something like
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png"));
request += "image=" + URLEncode(image);
No changes needed on the server side. Just find out what the system call is to URL Encode a piece of string.
Upvotes: 5
Reputation: 49215
I will suggest two things to try out
Include charset in content type as your are relying on UTF8 -
rq.ContentType = "application/x-www-form-urlencoded; charset=utf-8"
Use StreamWriter to write to request stream as you are using StreamReader to read it.
Upvotes: 0