java实现网易云短信接口

xiaoxiao2021-02-28  41

httpclient-4.3.6.jar和httpcore-4.3.3.jar jar包

首先去网易云注册账号得到分配的app key 和 App Secret  开通短信有20条试用。使用的是httpclient post提交

请求信息分为 请求头和请求参数

 请求头:必须5个参数,分别是:AppKey。Nonce。CurTime。CheckSum。Content-Type。  区分大小写

 请求参数:mobile(手机号码),code(验证码),templateid(模板id),codeLen(验证码长度)  非必填的。

 创建一个生成随机验证码的类:

import java.security.MessageDigest;/** * 验证码生成工具类 */public class CheckSumBuilder {    // 计算并获取CheckSum    public static String getCheckSum(String appSecret, String nonce, String curTime) {        return encode("sha1", appSecret + nonce + curTime);    }    // 计算并获取md5值    public static String getMD5(String requestBody) {        return encode("md5", requestBody);    }    private static String encode(String algorithm, String value) {        if (value == null) {            return null;        }        try {            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);            messageDigest.update(value.getBytes());            return getFormattedText(messageDigest.digest());        } catch (Exception e) {            throw new RuntimeException(e);        }    }    private static String getFormattedText(byte[] bytes) {        int len = bytes.length;        StringBuilder buf = new StringBuilder(len * 2);        for (int j = 0; j < len; j++) {            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);        }        return buf.toString();    }    private static final char[] HEX_DIGITS =            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};}

根据api提供的java代码创建一个测试类

import com.alibaba.fastjson.JSON;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Map;/**

*发送请求到网易云

*success:网易云成功发送验证码到手机

*/public class SendCode {    public static void main(String[] args) throws Exception {            System.out.println(sendMsg("******************"));    }    private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";//发送验证码的请求路径URL    private static final String APP_KEY = "***************************************";//网易云信分配的账号    private static final String APP_SECRET = "*********";//网易云信分配的密钥    private static final String NONCE = "123456";//随机数    //短信模板ID    private static final String TEMPLATEID="3094150";    //验证码长度,范围4~10,默认为4    private static final String CODELEN="6";    /**     *      * @param phone  手机号     * @return     * @throws IOException     */    public static MessageVo sendMsg(String phone) throws IOException {            CloseableHttpClient httpclient = HttpClients.createDefault();        HttpPost post = new HttpPost(SERVER_URL);        String curTime = String.valueOf((new Date().getTime() / 1000L));        /*通过验证码工具类生成随机数*/        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);        System.out.println("验证码:"+checkSum);        //设置请求的header  请求头        post.addHeader("AppKey", APP_KEY);        post.addHeader("Nonce", NONCE);        post.addHeader("CurTime", curTime);        post.addHeader("CheckSum", checkSum);        post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");        //设置请求参数        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        /*启用短信模板*/        nameValuePairs.add(new BasicNameValuePair("templateid", TEMPLATEID));        /*手机号*/        nameValuePairs.add(new BasicNameValuePair("mobile",phone));        /*验证码长度*/        nameValuePairs.add(new BasicNameValuePair("codeLen",CODELEN));        /*将请求头信息和请求参数放入一个entity里面*/        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));        //执行请求        HttpResponse response = httpclient.execute(post);        /*获取返回的信息 是一个json字符串*/        String responseEntity = EntityUtils.toString(response.getEntity(),"utf-8");        MessageVo messageVo=new MessageVo();        //判断是否发送成功,发送成功返回true  获取返回的状态码        String code = JSON.parseObject(responseEntity).getString("code")

        System.out.println("状态吗:"+code);        messageVo.setCode(code);        messageVo.setObj(obj);        return messageVo;

//        if (code.equals("200")) {//            return "success";//        }//        return "error";    }}

然后就是一个输入手机号码和验证码的校验类

import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;import com.alibaba.fastjson.JSON;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/** * 校验验证码输入是否正确 */public class MobileMessageCheck {    public static void main(String[] args) throws Exception {        System.out.println(checkMsg("187********","626712"));    }    private static final String SERVER_URL = "https://api.netease.im/sms/verifycode.action";//校验验证码的请求路径URL    private static final String APP_KEY = "*********************************";//网易云信分配的账号    private static final String APP_SECRET = "***************";//网易云信分配的密钥    private static final String NONCE = "123456";//随机数      /**     *      * @param phone  手机号     * @param sum     验证码     * @return     * @throws IOException     */    public static MessageVo checkMsg(String phone, String sum) throws IOException {        CloseableHttpClient httpclient = HttpClients.createDefault();        HttpPost post = new HttpPost(SERVER_URL);        String curTime = String.valueOf((new Date().getTime() / 1000L));        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);        //设置请求的header        post.addHeader("AppKey", APP_KEY);        post.addHeader("Nonce", NONCE);        post.addHeader("CurTime", curTime);        post.addHeader("CheckSum", checkSum);        post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");        //设置请求参数        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        nameValuePairs.add(new BasicNameValuePair("mobile", phone));        nameValuePairs.add(new BasicNameValuePair("code", sum));        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));        //执行请求        HttpResponse response = httpclient.execute(post);        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");        MessageVo messageVo=new MessageVo();        //判断是否发送成功,发送成功返回true        String code = JSON.parseObject(responseEntity).getString("code");

        System.out.println("状态吗:"+code);        messageVo.setCode(code);        return messageVo;//        if (code.equals("200")) {//           return "success";//        }//        return "error";    }}

创建实体类MessageVo用来存储状态码与验证码属性

package cn.vo; public class MessageVo {  private String code;//状态码  private String obj;//验证码  public String getCode() {   return code;  }  public void setCode(String code) {   this.code = code;  }  public String getObj() {   return obj;  }  public void setObj(String obj) {   this.obj = obj;  }   }

创建UsreServlet类,与jsp互动。通过ajax传值,判断

public class UserServlet extends HttpServlet {  public void service(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {   request.setCharacterEncoding("utf-8");   response.setContentType("text/html;charset=utf-8");   String action = request.getParameter("action");      if(action.equals("verifyingCode")){    //发送请求到网易云,返回请求处理状态    String phone = request.getParameter("phone");    MessageVo messageVo= SendCode.sendMsg(phone);    String code=messageVo.getCode();    if(code.endsWith("200")){     //将验证码塞入session,可以这样就可以自己写验证验证码的方法了,     request.getSession().setAttribute("verifyingCode", messageVo.getObj());     response.getWriter().print("success");    }else{     response.getWriter().print("error");    }   }else if(action.equals("register")){    //检测验证码是否正确,这个是调用网易云平台的方法检验,也可以自己写代码检验  //  String  phone = request.getParameter("phone"); //   System.out.println(phone);      String yzmStr = request.getsession().getAttribute("verifyingCode");     System.out.println(yzmStr);      String yzm = request.getParameter("yzm");      System.out.println(yzm); //   MessageVo messageVo= MobileMessageCheck.checkMsg(phone, yzm); //   String code=messageVo.getCode(); //   if(code.endsWith("200")){ //    response.getWriter().print("success");  //  }else{ //    response.getWriter().print("error"); if(yzm.equals(yzmStr)){     response.getWriter().print("success"); }else{     response.gerWriter().print("error"); }    }   }  } }

前台Ajax代码

<script type="text/javascript">  $(document).ready(function() {   var min = 60;   var time;   $("#yzm").click(function(){        var phone = $("#phone").val();    $.ajax({                       url:"http://localhost:8080/web0706msg/UserServlet",                      type:"post",                     data:{"action":"verifyingCode","phone": phone},                    success:function(e){                         if(e=="success"){                         alert("验证码发送成功!");                         if(min != 60){                    return;                   }                   fun();                   time = setInterval(fun,1000);                                                }else{                         alert("验证码发送失败!");                        }                    }                 });    });      function fun(){    min = --min;    if(min > 0){     $("#yzm").html("("+min+")秒后重发");    } else {     clearInterval(time);     min = 60;     $("#yzm").html("获取验证码");    }   }  });  $(".tableBtn").click(function(){ //  alert("111")   var phone = $("#phone").val();   var yzm =$("[name=yzm]").val();   $.ajax({                   url:"http://localhost:8080/web0706msg/UserServlet",                  type:"post",                 data:{"action":"register","phone": phone,"yzm":yzm},                success:function(e){                     if(e=="success"){                   // alert("验证码验证成功!");                    }else if(e=="error"){                   // alert("验证码验证失败!");                    }                }             });   });     </script>

转载请注明原文地址: https://www.6miu.com/read-2620085.html

最新回复(0)