前言:微信小程序需要生成二维码,后台通过微信api获取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/json"; 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[] string guid = Guid.NewGuid().ToString(); System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Content/img/"+ guid + ".jpg"), tt); return "https://*********/Content/img/" + guid + ".jpg"; } 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; } } }
///将数据流转为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(); }
调用上面Api_Post方法
string strUrlPara = "{\"page\":\"" + page + "\",\"scene\":" + scene + "}"; string url= "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=**************"; string resu = Api_Post(url, strUrlPara, null, true);