C#在httpclient下访问某第三方短信验证码平台API

//配置文件
 <appSettings>
   《《add key="webpages:Version" value="2.0.0.0" /》
    《add key="webpages:Enabled" value="false" /》
    《add key="PreserveLoginUrl" value="true" /》
   《add key="ClientValidationEnabled" value="true" /》
    《add key="UnobtrusiveJavaScriptEnabled" value="true" /》
    《add key="WebReference.Service.PostUrl" value="http://106.ihuyi.com/webservice/sms.php?method=Submit"/》//重点

  </appSettings>

///以上是web.confing中的配置

后台Httpclient访问API代码

public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];//是在web.confing配置的数据
public string yzm(string mobiles)
        {
            if (mobiles != null)
            {
                string account = "********";//用户名是登录ihuyi.com账号名(例如:cf_demo123)
                string password = "**********************"; //请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
                string mobile = mobiles;
                Random rad = new Random();//生成随机数
                int mobile_code = rad.Next(1000, 10000);
                string content = "您的验证码是:" + mobile_code + " 。请不要把验证码泄露给其他人。";//要发送的内容

                //Session["mobile"] = mobile;

                string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}&format={4}";//拼接字符串形成请求体
                using (HttpClient client = new HttpClient())//用客户端请求API数据
                {
                    //进行utf-8进行编码解析;因为API接口需要密文以字节数组的形式发送
                    UTF8Encoding encoding = new UTF8Encoding();
                    //将请求体编码成字节数组
                    byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content, "json"));
                    //设置请求体
                    HttpContent contents = new ByteArrayContent(postData, 0, postData.Length);
                    //设置请求头(包头)成字节数组
                    contents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    //请求结果
                    var result = client.PostAsync(PostUrl, contents).Result;
                    //判断请求结果的状态码
                    if (result.IsSuccessStatusCode)
                    {
                        //返回的json结果
                        var jj = result.Content.ReadAsStringAsync().Result;
                       //已发送的验证码
                        //Session["mobile_code"] = mobile_code;//可以那此值与客户输入的验证码作比较。
                        return jj;
                    }
                    else
                    {
                        var jj = result.StatusCode;
                        return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
                    }
                }

            }

                return Newtonsoft.Json.JsonConvert.SerializeObject({"code:1"});

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值