2

好的,所以问题是我试图通过编码为 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);
4

2 回答 2

5

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.

于 2010-08-20T13:49:11.790 回答
0

我将建议尝试两件事

  1. 在内容类型中包含字符集,因为您依赖 UTF8 -

    rq.ContentType = "应用程序/x-www-form-urlencoded; charset=utf-8"

  2. 使用 StreamWriter 写入请求流,就像使用 StreamReader 读取它一样。

于 2010-08-20T12:59:33.837 回答