【问题标题】:Issue sending a base64 encoded string via HTTP with .NET使用 .NET 通过 HTTP 发送 base64 编码字符串的问题
【发布时间】:2011-04-01 14:04:54
【问题描述】:

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

【问题讨论】:

  • 请提供示例代码,或至少指定您发送值的何处,例如正文或 URL。
  • 另外,您知道如果通过 GET 参数发送,这有大小限制吗?
  • 我正在发布它。稍后我会添加代码sn-p。

标签: .net http base64 transmission


【解决方案1】:

下面的第二行是问题。

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 编码的系统调用是什么。

【讨论】:

  • 是的,以前被这个刺痛过!
【解决方案2】:

我会推荐两件事来尝试

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

    rq.ContentType = "application/x-www-form-urlencoded; charset=utf-8"

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多