首页 > 编程语言 >.net通过数据流的方式,HttpWebRequest请求小程序二维码

.net通过数据流的方式,HttpWebRequest请求小程序二维码

时间:2022-09-20 16:35:29浏览次数:81  
标签:string color scene wbRequest HttpWebRequest 数据流 new net page

#region
        /// <summary>
        /// 获取小程序页面的小程序码 不限制
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
        /// <param name="scene">最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)</param>
        /// <param name="page">必须是已经发布的小程序页面,例如 "pages/index/index" ,根路径前不要填加'/',不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面</param>
        /// <param name="width">小程序码的宽度</param>
        /// <param name="auto_color">自动配置线条颜色</param>
        /// <returns></returns>
        public static async Task<Stream> GetWxaCodeUnlimitTest(string accessTokenOrAppId,
            string scene, string page, int width = 430, bool auto_color = false)
        {

            var authInfo = await AuthorizerContainer.GetAuthorizationInfoAsync(WxOpenConfig.ComponentAppID, accessTokenOrAppId);
            var authorizer_access_token = authInfo.authorizer_access_token;

            Stream streamAA = new MemoryStream();

            //小程序参数
            string paramData = "&scene=" + scene
                        + "&page=" + page
                        + "&width=" + width
                        + "&authInfo=" + authInfo
                        + "&auto_color=" + auto_color;
            var data = new { scene = scene, page = page, width = width, auto_color = auto_color };
            string json = data.ToJson();
            byte[] load = Encoding.UTF8.GetBytes(json);
            //小程序请求接口
            string urlFormat = TMConfig.ApiMpHost + "/wxa/getwxacodeunlimit?access_token={0}";
            string urlGet = string.Format(urlFormat, authorizer_access_token);

            //发起请求
            HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(urlGet);
            wbRequest.Method = "POST";
            wbRequest.ContentType = "application/json;charset=UTF-8";

            wbRequest.ContentLength = load.Length;
            using (Stream writer = wbRequest.GetRequestStream())
            {
                writer.Write(load, 0, load.Length);
            }

            //接收返回包
            string resultJson = string.Empty;
            HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
            using (Stream responseStream = wbResponse.GetResponseStream())
            {
                //将数据流转为byte[]
                List<byte> bytes = new List<byte>();
                int temp = responseStream.ReadByte();
                while (temp != -1)
                {
                    bytes.Add((byte)temp);
                    temp = responseStream.ReadByte();
                }
                byte[] mg = bytes.ToArray();

                //在文件名前面加上时间,以防重名  
                string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
                //文件存储相对于当前应用目录的虚拟目录  
                string path = "/imageAAA/";
                //获取相对于应用的基目录,创建目录  
                string imgPath = System.AppDomain.CurrentDomain.BaseDirectory + path;     //通过此对象获取文件名  
                //StringHelper.CreateDirectory(imgPath);//创建文件夹
                System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(path + imgName), mg);//讲byte[]存储为图片  
            }

            return streamAA;
        }
        #endregion

 

/// <summary>
    /// 小程序二维码线条颜色(RGB颜色)
    /// </summary>
    public class LineColor
    {
        /// <summary>
        /// 红色
        /// </summary>
        public int r { get; set; }
        /// <summary>
        /// 绿色
        /// </summary>
        public int g { get; set; }
        /// <summary>
        /// 蓝色
        /// </summary>
        public int b { get; set; }
}

 

/// <summary>
        /// 获取小程序页面的小程序码的流,次数不限制,如果出错,返回错误消息
        /// </summary>
        /// <param name="authorizer_access_token"></param>
        /// <param name="scene"></param>
        /// <param name="page"></param>
        /// <param name="width"></param>
        /// <param name="auto_color"></param>
        /// <param name="line_color"></param>
        /// <param name="is_hyaline"></param>
        /// <returns></returns>
        public static async Task<Dictionary<string, object>> GetWxaCodeUnlimitStreamMsgAsync(
            string authorizer_access_token,
            string scene,
            string page,
            int width = 430,
            bool auto_color = false,
            LineColor line_color = null,
            bool is_hyaline = false)
        {
////小程序参数
            //string paramData = "&scene=" + scene
            //            + "&page=" + page
            //            + "&width=" + width
            //            + "&auto_color=" + auto_color
            //            + "&line_color=" + line_color
            //            + "&is_hyaline=" + is_hyaline;
            var data = new { scene = scene, page = page, width = width, auto_color = auto_color, line_color = line_color, is_hyaline = is_hyaline };
            string paramJson = data.ToJson();

            //小程序请求接口
            string urlFormat = TMConfig.ApiMpHost + "/wxa/getwxacodeunlimit?access_token={0}";
            string urlGet = string.Format(urlFormat, authorizer_access_token);

            return await RequestUtility.HttpResponseStreamMsgAsync(urlGet, paramJson);
        }

 

/// <summary>
        /// 获取微信小程序二维码的流,如果出错,返回错误消息
        /// </summary>
        /// <param name="urlGet"></param>
        /// <param name="paramJson"></param>
        /// <returns></returns>
        public async static Task<Dictionary<string, object>> HttpResponseStreamMsgAsync(string urlGet, string paramJson)
        {
            string currentMethodLog = "[HttpResponseStreamAsyncTest()]获取小程序二维码的流,";
            try
            {
                //发起请求
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(urlGet);
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/json;charset=UTF-8";

                byte[] load = Encoding.UTF8.GetBytes(paramJson);
                wbRequest.ContentLength = load.Length;
                using (Stream writer = wbRequest.GetRequestStream())
                {
                    writer.Write(load, 0, load.Length);
                }

                //接收返回包               
                HttpWebResponse wbResponse = (HttpWebResponse)(await wbRequest.GetResponseAsync());
                Stream streamSuccess = new MemoryStream();
                Stream streamFail = new MemoryStream();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    //将数据流转为byte[]
                    List<byte> bytes = new List<byte>();
                    int temp = responseStream.ReadByte();
                    while (temp != -1)
                    {
                        bytes.Add((byte)temp);
                        temp = responseStream.ReadByte();
                    }
                    byte[] mg = bytes.ToArray();

                    streamSuccess = new MemoryStream(mg);
                    streamFail = new MemoryStream(mg);

                    //如果请求成功会直接返回数据流,
                    //如果请求失败会返回Json,例如:
                    //{"errcode":61004,"errmsg":"access clientip is not registered hint: [aHCZjA05601518]"}
                    //{"errcode":61004,"errmsg":"access clientip is not registered hint: [aHCZjA05601518]"}
                    try
                    {
                        //返回失败
                        StreamReader sread = new StreamReader(streamFail);
                        string result = sread.ReadToEnd();
                        Dictionary<string, string> dicResult = JsonExt.ToObject<Dictionary<string, string>>(result);
                        Log4NetHelper.Log(LogTypeEnum.ServicesLog, LogLevelEnum.Error,
                          "接收微信返回错误消息:" + result);
                        streamSuccess.Dispose();//释放成功流的资源
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("FAIL", result);
                        return dic;
                    }
                    catch (Exception ex)
                    {
                        //返回成功
                        streamFail.Dispose();//释放失败流的资源
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("SUCCESS", streamSuccess);
                        return dic;
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.Log(LogTypeEnum.ServicesLog, LogLevelEnum.Error,
                    currentMethodLog + "接口报错:", ex);
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("FAIL", currentMethodLog + "接口报错:" + ex.Message);
                return dic;
            }
        }

 

//获取小程序二维码的流
            var resultDic = await WxAppApi.GetWxaCodeUnlimitStreamMsgAsync(authorizer_access_token, scene, page);
            if (resultDic.First().Key.Equals("FAIL"))
            {
                response.Status = BaseResponseStatusEnum.Error;
                response.Msg = resultDic.First().Value.ToString();
                return response;
            }
            Stream wXQrCodePicStream = resultDic.First().Value as Stream;

 

搜索

复制

标签:string,color,scene,wbRequest,HttpWebRequest,数据流,new,net,page
From: https://www.cnblogs.com/jankie1122/p/11108639.html

相关文章

  • C# .net 对外接口返回json字符串序列化
     UserBankCarduserBankCard=newUserBankCard(){BankCard=bankCard,UserID=userID,RealName......
  • .NET 6 EFCore WebApi 使用 JMeter 进行吞吐量测试
    .NET6EFCoreWebApi使用JMeter进行吞吐量测试开发环境VS2022.NET6测试环境测试工具接口压力测试工具:JMeter数据库MySQL5.7数据库和WebApi服务在同一台服务......
  • DropoutNet: Addressing Cold Start in Recommender Systems阅读笔记
    动机本文是2017年nips上的一篇论文。在当时对于冷启动问题,大部分工作是针对colditem的,或是将偏好和内容都结合在目标函数中使其非常复杂。本文作者提出了DropoutNet,这个......
  • .net 前端传值给后端有几种方法
    .net前端传值给后端有几种方法常用的一.html的标签form表单传值二.jquery的Ajax提交(可以用js里面的Ajax)$.ajax({url:"/index",//后端地址......
  • Net5 控制台程序读取配置文件的几种方式
    十年河东,十年河西,莫欺少年穷学无止境,精益求精本篇提供几种读取配置文件的方式,从简到难,步步加深1、新建控制台程序1.1、新增一个名称为application.json的配置文件appl......
  • .NET6发布程序报错发布遇到错误。生成失败。检查输出窗口了解更多详细信息。
    发布报错详情:发布遇到错误。生成失败。检查输出窗口了解更多详细信息。已将诊断日志写入以下位置:“C:\Users\USER\AppData\Local\Temp\tmpD5F7.tmp”。解决方案:在项目......
  • .Net6 IPv6使用
          表示方法IPv6的长分布式结构图IPv6的长分布式结构图IPv6的地址长度为128位,是IPv4地址长度的4倍。于是IPv4点分十进制格式不再适用,采用十六进制表示。I......
  • AspNetUsers锁定用户
    SetLockoutEnabledAsync SetLockoutEndDateAsync控制台显示警告:数据库未被更改Lockoutisnotenabledforthisuser.AspNetUsers表中字段LockoutEnabled表示“是否......
  • .netcore发布后错误排查
    1、.dll不能运行,iis没有显示错误,可能是发布后是生产环境,该为开发环境,修改web.config<aspNetCoreprocessPath="dotnet"arguments=".\CoreCms.Wrl.Web.dll"stdoutLogEna......
  • .net Ioc 详解
    一、概念1.1什么是IOC?Ioc—InversionofControl,即 控制反转,其是一种 设计思想,而不是一种技术。在没有使用IOC之前,我们一般是通过new来实例化,从而创建一个对象。但是......