首页 > Windows开发 > 详细

C# POST数据base64到接口会出错的问题

时间:2016-11-24 06:56:01      阅读:431      评论:0      收藏:0      [点我收藏+]


这个base64在requestHeader里面变成了
base64=hySGNg22yX0AIjNQvNJw0xHEbi32NH%2BiRVKDkbOmUiKpxW0%2FS6rUgfLmSa527Y8zZ3GmEzfXMB8ry8fH5GjGeJFGqFxDC4A2hLlvIFzyiDeUCqloGDAJoOLa8Jnif1C8nwRte0GNCRM5RXkshLKZP2itZclgDCYz6OgAF7oLNluoB44cZ3AgF1Q8hVgME8LeqgOqxsIzTt3Xn%2B96j7zp%2FwA%3D

他把base64里面一些/和= 给转成%2F之类的东西了。

所以webservice接收到的参数是错的。。


解决办法:

 

string base64 = "base64=hySGNg22yX0AIjNQvNJw0xHEbi32NH+iRVKDkbOmUiKpxW0/S6rUgfLmSa527Y8zZ3GmEzfXMB8ry8fH5GjGeJFGqFxDC4A2hLlvIFzyiDeUCqloGDAJoOLa8Jnif1C8nwRte0GNCRM5RXkshLKZP2itZclgDCYz6OgAF7oLNluoB44cZ3AgF1Q8hVgME8LeqgOqxsIzTt3Xn+96j7zp/wA=";
byte[] buffer = Convert.FromBase64String(base64);
string Base64StrData = Convert.ToBase64String(buffer).Replace("+", "%2B");//注意加号(’+‘)的替换处理,否则由于加号经过Url传递后变成空格而得不到合法的Base64字符串
        string postData = "str=" + Base64StrData;
    byte[] dataArray = Encoding.Default.GetBytes(postData);

 

/// <summary>
        /// POST请求与获取结果
        /// </summary>
        public static string HttpPost(string Url, string postDataStr)
        {
            try
            {
                postDataStr = postDataStr.Replace("+", "%2B");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.Timeout = 6000000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataStr.Length;
                StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                writer.Write(postDataStr);
                writer.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string retString = reader.ReadToEnd();
                return retString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 

C# POST数据base64到接口会出错的问题

原文:http://www.cnblogs.com/testsec/p/6095818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!