前言
昨天因为小程序功能要获取小程序程序码,看了微信文档爬了好多坑。(留一下记录以防后面被坑)
操作
因为我获取到了微信那里的图片的图片流一直不知道怎么处理,今天总算找到相关文档,解决了。因为数据流不能直接传给前端,只好把buffer流转成图片保存在服务器上,没办法啊~
废话不多说上代码
public static string Api_Post(string postUrl, string postData, WebHeaderCollection header = null,bool isPic=false)
{ Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(postUrl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (header != null) request.Headers = header; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream();
if (isPic) { byte[] tt = StreamToBytes(instream);//将数据流转为byte[] System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/WxCode.jpg"), tt); WxQRCodeModel model = new WxQRCodeModel(); model.data = "192.168.1.216:80/WxCode.jpg"; model.errcode = 0; string content = Config.js.Serialize(model); string err = string.Empty; return content; } else { sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } } catch (Exception ex) { if (isPic) { sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } else { string err = ex.Message; return string.Empty; } } }
因为是instream接受到微信接口那里发送过来的数据流,就在instream那里处理,把数据流转换为byte[]数组,然后依靠File的WriteAllBytes方法把转换OK的byte[]数组转换为图片存放在服务器上,然后把图片路径交给model。
///将数据流转为byte[] public static byte[] StreamToBytes(Stream stream) { List<byte> bytes = new List<byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } return bytes.ToArray(); }
结尾
最近才接触到微信小程序开发,emmmm。觉得自己摸鱼摸得好厉害,不过终于把坑爬出来,特别开心。哈哈哈~以后要多多写开发记录。上班期间码得很随意