Sending base64 string using HttpWebRequest in C # convert "+" to space issue
i convert image to base64 string for upload via HttpWebRequest in c # .on server side, when i get base64 string, "+" signs were converted to white spaces ". it gives me error to convert this base64 string to byte array. i do not want to make any changes on the server side (in web services) I want to solve these problems on the client side The client code of the client is as follows.
//////////////////
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 is the base 64-line gene evaluated from the image
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;
All "+" signs in the base64 string are converted to "white spaces". This causes the problem described above.
Please help me to solve this problem.
Hello
Shah Khalid
source to share
There is an encoding called Base64Url encode that does just that. However, you might have to do encoding / decoding at your respective ends.
In Base64 Url it converts +
to -
and /
to _
so that it can be transmitted safely over the wire without standard url encoders, adding oddities like spaces or percent-hex
source to share
thanks for Rob.it to solve my problem by replacing "+" with hexadecimal "% 2B" on the client side to send data via wire.as below in 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");
source to share