知识学堂 > 课程 > 小程序海报

小程序海报

发布日期:2025/6/18 来源:聚恒【返回】

类-post方法


    public static string Post_biaotou_1(string xml, string url, bool isUseCert, int timeout, Dictionary<string, string> dic = null)
    {
        System.GC.Collect();
        byte[] imageBuffer = null;

        HttpWebRequest request = null;
        HttpWebResponse response = null;
        Stream reqStream = null;
        string fileName = Guid.NewGuid() + ".jpg";
        try
        {
            ServicePointManager.DefaultConnectionLimit = 200;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = timeout * 1000;
            request.ContentType = "application/json";

            if (dic != null && dic.Count != 0)
            {
                foreach (var item in dic)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }

            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            request.ContentLength = data.Length;

            if (isUseCert)
            {
                X509Certificate2 cer = new X509Certificate2(WxPayConfig.SSLCERT_PATH,
                    WxPayConfig.SSLCERT_PASSWORD,
                    X509KeyStorageFlags.MachineKeySet |
                    X509KeyStorageFlags.PersistKeySet |
                    X509KeyStorageFlags.Exportable);
                request.ClientCertificates.Add(cer);
            }

            reqStream = request.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();

            response = (HttpWebResponse)request.GetResponse();

            using (MemoryStream ms = new MemoryStream())
            {
                response.GetResponseStream().CopyTo(ms);
                imageBuffer = ms.ToArray();
            }

            // 新增:保存图片到update文件夹
            if (imageBuffer != null && imageBuffer.Length > 0)
            {
                string saveDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");
               // Log.Info("HttpService", "saveDir: " + saveDir);
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }

             
                string filePath = Path.Combine(saveDir, fileName);
                File.WriteAllBytes(filePath, imageBuffer);
                return fileName;
            }
        }
        catch (System.Threading.ThreadAbortException e)
        {
            Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
            Log.Error("Exception message: {0}", e.Message);
            System.Threading.Thread.ResetAbort();
            throw;
        }
        catch (WebException e)
        {
            Log.Error("HttpService", e.ToString());
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
            }
            throw new WxPayException(e.ToString());
        }
        catch (Exception e)
        {
            Log.Error("HttpService", e.ToString());
            throw new WxPayException(e.ToString());
        }
        finally
        {
            if (response != null) response.Close();
            if (request != null) request.Abort();
        }

        return fileName;
    }

 

ashx调用

 private void panduan(HttpContext context)
 {
     try
     {
         string openId = SqlZhuRu.InputTextSql(context.Request.Form["openid"]);
         // 方法1:正则表达式去除非字母数字字符

         string cleaned = Regex.Replace(openId, @"[^\w-]", "");

         // 方法2:验证长度(可选)
         if (cleaned.Length != 28)
         {
             SendResponse(context, new { code = 400, message = "处理后的openid长度异常,请检查原始数据" });
             return;
         }

         string fanhui = "";
         try
         {
             BLL.UserManager User_bll = new BLL.UserManager();
             Model.User Users = new Model.User();
             Users = User_bll.Query_User(" and username='" + openId + "'", "");

             WebClient client = new WebClient();
             string pd = (string)HttpRuntime.Cache["access_token"];
             if (pd == null)
             {
                 string AccessTokenURL = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WxPayConfig.APPID, WxPayConfig.APPSECRET);
                 client.Encoding = System.Text.Encoding.UTF8;
                 var result2 = client.DownloadString(AccessTokenURL);
                 JsonData jd2 = JsonMapper.ToObject(result2);

                 Log.Info("生成小程序码access_token1", jd2.ToJson());

                 string access_token = (string)jd2["access_token"];
                 HttpRuntime.Cache.Insert("access_token", access_token, null, DateTime.Now.AddHours(2), System.Web.Caching.Cache.NoSlidingExpiration);
                 pd = (string)HttpRuntime.Cache["access_token"];

             }

             string json = "{\"page\":\"pages/Identity/Identity\",\"scene\": \"yqm=" + Users.remark + "\",\"check_path\": false,\"env_version\": \"develop\"}";

             //env_version正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。

             string erweima_fanhui = HttpService.Post_biaotou_1(json, "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + pd, false, 10);

 

 

             Log.Info("生成小程序码", erweima_fanhui);

 

             BLL.LinkManager bll_Link = new BLL.LinkManager();
             int jishu = bll_Link.Query_Link(" and content='签到' and title='" + openId + "' and link='" + DateTime.Now.ToString("yyyy-MM-dd") + "'");

             fanhui = JsonConvert.SerializeObject(new { code = 0, photo = Users.photo, erweima ="https://************/Upload/"+erweima_fanhui, truename = Users.truename, recommend = Users.recommend, remark = Users.remark, qiandao = jishu > 0 ? true : false });
         }
         catch (Exception ex)
         {
             fanhui = JsonConvert.SerializeObject(new { code = 0, message = ex.Message });
         }
         context.Response.ContentType = "application/x-www-form-urlencoded";
         context.Response.Write(fanhui);
     }
     catch (Exception ex)
     {
         SendResponse(context, new { code = 500, message = ex.Message });
     }
 }