gpt4 book ai didi

c# - 在 c# 中使用 HttpWebRequest 发送 base64 字符串将 "+"转换为空白问题

转载 作者:太空狗 更新时间:2023-10-30 00:55:18 27 4
gpt4 key购买 nike

我将图像转换为 base64 字符串以通过 C# 中的 HttpWebRequest 上传。在服务器端,当我收到 base64 字符串时,“+”符号已转换为空格“”。将此 base64 字符串转换为字节数组时出错。我不想在服务器端(在 Web 服务中)进行任何更改。我想在客户端解决这个问题。我的客户端代码如下。

/////////////////

WSManagerResult wsResult = new WSManagerResult();

        try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(serviceURL);
req.Method = "POST";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentType = "application/x-www-form-urlencoded";
// req.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
// req.CookieContainer = new CookieContainer();


string content = string.Empty;
foreach (KeyValuePair<string, string> entry in paramDic)
{

//entry.Value 是根据图像评分的 base 64 字符串基因

             content = content + entry.Key + "=" + entry.Value + "&&";
}
content = content.TrimEnd('&'); // input parameter if u have more that one //a=b&dd=aa
req.ContentLength = content.Length;
// req = URLEncode(content);
Stream wri = req.GetRequestStream();


byte[] array = Encoding.ASCII.GetBytes(content);
if (array.Length > 0)
wri.Write(array, 0, array.Length);
wri.Flush();
wri.Close();
WebResponse rsp = (HttpWebResponse)req.GetResponse();


byte[] b = null;
using (Stream stream = rsp.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
b = ms.ToArray();
}
wsResult.result = Encoding.ASCII.GetString(b);
}
catch (Exception e)
{
clsException.ExceptionInstance.HandleException(e);
wsResult.error = e.Message;
}


return wsResult;

上述 base64 字符串中的所有“+”符号都被转换为“”空格。这会导致上述问题。

请帮我解决这个问题。

问候

沙哈立德

最佳答案

非常感谢 Rob。它通过在客户端将“+”替换为十六进制“%2B”以通过 wire 发布数据来解决我的问题。如下面的 c# 所示。

/*Using standard Base64 in URL requires encoding of '+', '/' and '=' characters into special percent-encoded hexadecimal sequences ('+' = '%2B', '/' = '%2F' and '=' = '%3D')*/ 

String stbase64datatopost =stbase64datatopost.Replace("+",@"%2B");
stbase64datatopost = stbase64datatopost .Replace("/",@"%2F");
stbase64datatopost=stbase64datatopost.Replace("=",@"%3D");

关于c# - 在 c# 中使用 HttpWebRequest 发送 base64 字符串将 "+"转换为空白问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10022985/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com