C#与.NET在企业内网系统、Windows服务中常见。用C#接入互亿无线预警通知接口,可在Windows服务、定时任务、ASP.NET后端自动下发告警。本文给出HttpClient示例并记录几个常见坑。 C#接入的接口与参数 短信接口 h…
C#与.NET在企业内网系统、Windows服务中常见。用C#接入互亿无线预警通知接口,可在Windows服务、定时任务、ASP.NET后端自动下发告警。本文给出HttpClient示例并记录几个常见坑。
C#接入的接口与参数
短信接口 https://api.ihuyi.com/sms/Submit.json ,语音接口 https://api.ihuyi.com/voice/vm 。表单参数account、password、mobile、content。
- account=APIID,password=APIKEY;
- mobile=接收手机号;
- content=通知内容;
- 返回JSON中code=2为提交成功。
C#发送短信代码示例
.NET Core/.NET 5+中使用HttpClient:
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
public class NotifyService {
private static readonly HttpClient http = new HttpClient();
public async Task<string> SendSmsAsync(string mobile, string content) {
var form = new Dictionary<string, string> {
{"account", "APIID"}, {"password", "APIKEY"},
{"mobile", mobile}, {"content", content}
};
var resp = await http.PostAsync(
"https://api.ihuyi.com/sms/Submit.json",
new FormUrlEncodedContent(form));
return await resp.Content.ReadAsStringAsync(); // code=2
}
}
C#接入常见踩坑记录
- HttpClient不要每次new一个,应静态复用,否则耗尽socket;
- 中文content由FormUrlEncodedContent自动编码,勿手动再编码;
- 老版本.NET Framework用WebClient时需手动设置TLS12;
- 异步方法勿用.Result阻塞,避免在ASP.NET中死锁。
HttpClient异步示例与踩坑
.NET平台推荐用HttpClient发送请求,下面这个异步示例加上了超时与返回解析,适合放进ASP.NET Core后台服务:
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
class SmsNotifier {
private static readonly HttpClient http = new HttpClient {
Timeout = TimeSpan.FromSeconds(10)
};
public static async Task<string> SendSmsAsync(string mobile, string content) {
var form = new Dictionary<string, string> {
{"account", "你的APIID"},
{"password", "你的APIKEY"},
{"mobile", mobile},
{"content", content}
};
var resp = await http.PostAsync(
"https://api.ihuyi.com/sms/Submit.json",
new FormUrlEncodedContent(form)
);
return await resp.Content.ReadAsStringAsync(); // code=2为提交成功
}
}
踩坑记录
- HttpClient不要用一次new一个:应复用静态实例,避免socket耗尽;
- 同步调用async方法时用.GetAwaiter().GetResult(),避免在UI线程死锁;
- FormUrlEncodedContent会自动按UTF-8编码中文,无需手动转义;
- 返回JSON可用Newtonsoft.Json或System.Text.Json反序列化,判断code字段。
常见报错排查
- 任务超时:检查服务器出网HTTPS,云环境注意代理配置;
- 返回code非2:打印返回体,按msg定位认证或模板问题;
- 语音通道:URL换成 https://api.ihuyi.com/voice/vm ,参数一致。
避开这几个坑,C#接入预警通道就很顺畅。前往注册免费试用获取密钥。