云信批量发送消息

        // 存放定时器,避免被回收
        static System.Threading.Timer[] timers;

        // 记录批次
        public static int ICOUNT = 0;
        static StringBuilder sbError = new StringBuilder();

        public static void Send()
        {
            #region 批量发送测试 每分钟最多120次,每次最多向500人发送
            // 读取接收方accid
            using (FileStream fs = File.OpenRead("ACCID_20180608.txt"))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    string str = sr.ReadToEnd();
                    if (String.IsNullOrWhiteSpace(str))
                    {
                        // 无接收方
                        return;
                    }
                    string[] strs = str.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    // 批次,每批最多500
                    int iBatch = (int)Math.Ceiling(strs.Length / 500.00);

                    // 切片存储 [单次][500用户]
                    string[][] arr = new string[iBatch][];
                    for (int i = 1; i <= iBatch; i++)
                    {
                        arr[i - 1] = strs.Skip((i - 1) * 500).Take(500).ToArray();
                    }

                    // [批次][单次][500用户] 每批 120*500
                    int iTarr = (int)Math.Ceiling(arr.Length / 120.00);
                    string[][][] tarr = new string[iTarr][][];

                    timers = new System.Threading.Timer[iTarr];
                    for (int i = 1; i <= iTarr; i++)
                    {
                        int index = i - 1;
                        // 每批次传送的数据
                        tarr[index] = arr.Skip(index * 120).Take(120).ToArray();

                        // 第一批立即执行,之后每70秒执行下一批 每批次只执行一次
                        timers[index] = new System.Threading.Timer(new System.Threading.TimerCallback(Send120), tarr[index], TimeSpan.FromSeconds(index * 70), TimeSpan.FromMinutes(0));
                    }
                }
            }
            #endregion
        }
// 调用接口,发送消息 public static void Send120(object state) { ++ICOUNT; Console.WriteLine($"----------------- {ICOUNT} ---------------------"); // 用户ID列表 string[][] arr = state as string[][]; // 每分钟最多120个请求 for (int i = 0; i < (arr.Length>120?120:arr.Length); i++) { Task<string> task = new Task<string>((o) => { dynamic d = o as dynamic; // 发送消息接口 string url = " https://api.netease.im/nimserver/msg/sendBatchMsg.action"; string param = string.Format("fromAccid={0}&toAccids={1}&type=0&body={2}", "发送方账号", JsonConvert.SerializeObject(d.data), JsonConvert.SerializeObject(new { msg = "要发送的消息!" })); // 费时任务 string sResult= IM_HttpPost(url, param); dynamic dResult = JsonConvert.DeserializeObject<dynamic>(sResult); if (dResult.code != "200") { // 记录出错的数据 sbError.Append(string.Join("\n\r", d.data)); } return dResult.code; }, new { index = i, data = arr[i] }); task.ContinueWith((t, o) => { Console.WriteLine($"次数:{o},返回值:{t.Result}"); }, i); task.Start(); } }

 

转载于:https://www.cnblogs.com/coder-soldier/p/9176604.html

### 关于网易验证码接口的使用说明 #### 接口概述 网易提供了用于发送验证码的功能,开发者可以通过其 API 调用来实现短验证码的发送和验证。该服务支持种类型的短模板,其中验证码模板是最常用的选项之一。 #### 配置与准备工作 为了成功调用网易的短验证码接口,需要完成以下配置工作: 1. **开通短功能**:登录网易控制台并启用短功能,在此过程中可以访问短模板管理和开发手册。 2. **创建或选择验证码模板**:在短模板管理页面中,可以选择默认模板或者自定义新的验证码模板。务必注意短规则,并记录下所选模板的 ID[^2]。 3. **获取 APP_KEY 和 APP_SECRET**:这些参数是身份认证所需的关键凭证,需从网易的 APP_KEY 管理界面中提取,并将其嵌入到代码中的相应位置[^3]。 #### 示例代码 以下是基于 Java 的示例代码片段,展示如何通过网易接口发送验证码: ```java import com.alibaba.fastjson.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class YunXinSmsSender { private static final String APP_KEY = "your_app_key"; // 替换为实际的APP_KEY private static final String APP_SECRET = "your_app_secret"; // 替换为实际的APP_SECRET private static final String MOULD_ID = "your_mould_id"; // 替换为实际的模板ID private static final String URL_PREFIX = "https://sms.api.163yun.com/v2/sendsms"; public static void sendSms(String phone, String code) throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("templateId", MOULD_ID); jsonObject.put("mobiles", new String[]{phone}); jsonObject.put("params", new String[]{code}); String body = "{\"templateId\":\"" + MOULD_ID + "\",\"mobiles\":[\"" + phone + "\"],\"params\":[\"" + code + "\"]}"; byte[] bytes = body.getBytes("utf-8"); URL url = new URL(URL_PREFIX); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.addRequestProperty("AppKey", APP_KEY); StringBuilder sb = new StringBuilder(); sb.append("appKey=").append(APP_KEY).append("&").append("timestamp=").append(System.currentTimeMillis()) .append("&").append("nonce=").append(Math.random()).append("&").append("signatureVersion=1.0&") .append("signature="); String signature = sign(sb.toString(), APP_SECRET); // 自定义签名函数 conn.addRequestProperty("Authorization", "Bearer " + signature); conn.getOutputStream().write(bytes); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } private static String sign(String data, String secret) { try { javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1"); mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1")); byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(rawHmac); } catch (Exception e) { throw new RuntimeException(e); } } } ``` 上述代码实现了向指定手机号码发送验证码的核心逻辑。它利用了 POST 请求方式来传递 JSON 数据结构给服务器端,并包含了必要的安全措施如 HMAC-SHA1 加密算法生成授权令牌[^4]。 #### 官方文档链接 更详情可参阅官方文档地址:<https://dev.yunxin.163.com/docs/product/IM即时通讯/服务端API文档/接口概述>[^4] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值