好的,问题是我试图通过编码为base64的http发送一个字节数组。虽然在另一端接收到的字符串与原始字符串的大小相同,但字符串本身并不相同,因此无法将字符串解码回原始字节数组。
另外,在发送字符串之前,我已经在客户端完成了base64的转换,一切正常。在它被发送之后,问题就出现了。
我有什么遗漏吗?有特殊的格式类型吗?我试过使用escapeData(),但字符串太大。
提前谢谢你
编辑:代码
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);
最佳答案
下面的第二行是问题所在。
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png"));
request += "image=" + image;
如果您查看Base 64 index table,最后两个字符(+和/)不是url安全的。因此,当您将其附加到请求时,必须对图像进行url编码。
我不是一个.net的人,但是第二行应该写得像
string image = Convert.ToBase64String(System.IO.File.ReadAllBytes("c:\temp.png"));
request += "image=" + URLEncode(image);
服务器端不需要更改。只需找出系统调用的url编码一段字符串。
关于.net - 通过.NET通过HTTP发送base64编码的字符串时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3529860/