前言
昨天因為小程序功能要獲取小程序程序碼,看了微信文檔爬了好多坑。(留一下記錄以防后面被坑)
操作
因為我獲取到了微信那里的圖片的圖片流一直不知道怎么處理,今天總算找到相關(guān)文檔,解決了。因為數(shù)據(jù)流不能直接傳給前端,只好把buffer流轉(zhuǎn)成圖片保存在服務(wù)器上,沒辦法啊~
廢話不多說上代碼
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); // 準(zhǔn)備請求... try { // 設(shè)置參數(shù) 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(); //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求 instream = response.GetResponseStream(); if (isPic) { byte[] tt = StreamToBytes(instream);//將數(shù)據(jù)流轉(zhuǎn)為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); //返回結(jié)果網(wǎng)頁(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } } catch (Exception ex) { if (isPic) { sr = new StreamReader(instream, encoding); //返回結(jié)果網(wǎng)頁(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } else { string err = ex.Message; return string.Empty; } } }
因為是instream接受到微信接口那里發(fā)送過來的數(shù)據(jù)流,就在instream那里處理,把數(shù)據(jù)流轉(zhuǎn)換為byte[]數(shù)組,然后依靠File的WriteAllBytes方法把轉(zhuǎn)換OK的byte[]數(shù)組轉(zhuǎn)換為圖片存放在服務(wù)器上,然后把圖片路徑交給model。
///將數(shù)據(jù)流轉(zhuǎn)為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(); }
結(jié)尾
最近才接觸到微信小程序開發(fā),emmmm。覺得自己摸魚摸得好厲害,不過終于把坑爬出來,特別開心。哈哈哈~以后要多多寫開發(fā)記錄。上班期間碼得很隨意
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對武林網(wǎng)的支持。
新聞熱點
疑難解答