Java实现发送短信验证验证码功能(上篇)

短信测试平台:网易云信。链接地址:https://netease.im/
jar包:httpcore-4.4.3.jar, httpclient-4.5.1.jar
Maven:

com.alibaba
fastjson
1.2.47

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.10</version>
</dependency>

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.3</version>
</dependency>

1,根据文档,创建一个发送类SendMessage.java

package com.tour.resource;

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;

public class SendMessage {
//发送验证码的请求路径URL
private static final String SERVER_URL=”https://api.netease.im/sms/sendcode.action”;
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
private static final String APP_KEY=”这里填写自己申请的app_key”;
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
private static final String APP_SECRET=”这里填写自己申请的APP_SECRET”;
//随机数
private static final String NONCE=”123456”;
//短信模板ID(模版默认为语音,如果想使用短信模版,请注释此模版)
private static final String TEMPLATEID=”这里填写自己申请的短信模板id”;
//手机号
// private static final String MOBILE=”****“;
//验证码长度,范围4~10,默认为4
private static final String CODELEN=”4”;

public static String sendMsg(String phone) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(SERVER_URL);

// CheckSum的计算
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<>();
    nameValuePairs.add(new BasicNameValuePair("mobile",phone));
   nameValuePairs.add(new BasicNameValuePair("templateid", TEMPLATEID));
    nameValuePairs.add(new BasicNameValuePair("codeLen", CODELEN));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

    //执行请求
    HttpResponse response=httpclient.execute(post);
    String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");
    System.out.println(responseEntity+"&responseEntity");
    //获取发送状态码
    String code= JSON.parseObject(responseEntity).getString("code");

    if (code.equals("200")){
        System.out.println("发送成功!");
        return "success";
    }else{
        System.out.println("发送失败!");
        return "error";
    }
}

}

如果在测试类中返回发送失败,可以打印code码,来对错误进行判断,也可以参考打印出的responseEntity值,来进行判断,当code码为200时,执行成功。常见的错误码见:http://dev.yunxin.163.com/docs/product/%E7%9F%AD%E4%BF%A1/%E7%9F%AD%E4%BF%A1%E7%8A%B6%E6%80%81%E7%A0%81

2,编写一个CheckSumBuilder.java

package com.tour.resource;

扫描二维码关注公众号,回复: 1534327 查看本文章

import java.security.MessageDigest;

public class CheckSumBuilder {

//计算并获取checkSum
public static String getCheckSum(String appSecret,String nonce,String curTime){
    return encode("SHA",appSecret+nonce+curTime);
}

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 sb=new StringBuilder(len*2);
    for(int $i=0;$i<len;$i++){
        sb.append(HEX_DIGITS[(bytes[$i]>>4)&0x0f]);
        sb.append(HEX_DIGITS[bytes[$i]&0x0f]);
    }
    return sb.toString();
}

private static final char[] HEX_DIGITS={'0','1','2','3','4','5','6',
        '7','8','9','a','b','c','d','e','f'};

}

3.编写一个发送测试类SendMsg.java

这里写图片描述
到此发送短证束。下面开始短信验证:
4.编写一个验证码验类MobileMessageCheck.java
package com.tour.resource;

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;

public class MobileMessageCheck {

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";//随机数

public static String checkMsg(String phone,String num) 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<>();
    nameValuePairs.add(new BasicNameValuePair("mobile",phone));
    nameValuePairs.add(new BasicNameValuePair("code",num));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

    //执行请求
    HttpResponse response=httpclient.execute(post);
    String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

    //判断是否发送成功,发送成功返回true
    String code= JSON.parseObject(responseEntity).getString("code");
    System.out.println(code);
    if (code.equals("200")){
        retur}}

“success”;
}
return “error”;
}
}

猜你喜欢

转载自blog.csdn.net/m0_37688047/article/details/80423471