java短信验证码接口(阿里云/聚合数据)

硅谷探秘者 2406 0 0

阿里云

pom文件

    <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    
    <dependency>
	  <groupId>com.aliyun</groupId>
	  <artifactId>aliyun-java-sdk-core</artifactId>
	  <version>4.0.3</version>
	</dependency>

java类

import java.security.SecureRandom;
import java.util.Random;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import net.sf.json.JSONObject;
/**
 * 短信验证码
 * @author 硅谷探秘者(jia)
 *
 */
public class SendSms {
	
	private static final String SYMBOLS = "0123456789";
    private static final Random RANDOM = new SecureRandom();
    
    /*
     * 随机生成验证码
     */
    public static String getNonce_str() {
		char[] nonceChars = new char[4];
		for (int index = 0; index < nonceChars.length; ++index) {
			nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
		}
		return new String(nonceChars);
	}
	
    /**
     * 发送验证码
     * @param phone 手机号
     * @return
     */
    public static String send(String phone) {
    	String code=getNonce_str();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", "**");//标签
        request.putQueryParameter("PhoneNumbers", phone);//手机号
        request.putQueryParameter("TemplateCode", "**");//模板
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            JSONObject object = JSONObject.fromObject(response.getData());
            if(object.getString("Code").equals("OK")){
                return code;
            }else{
                return null;
            }
        } catch (Exception e) {
        	return null;
        }
    }
    public static void main(String[] args) {
    	send("***");
	}
}

参考网址:https://api.aliyun.com


聚合数据

package com.dzqc.exam.service;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;
 
	/**
	*短信API服务调用示例代码 - 聚合数据
	*在线接口文档:http://www.juhe.cn/docs/54
**/
 
public class SendJuHeMsg {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
 
    //配置您申请的KEY
    public static final String APPKEY ="appkey";
 
    private static final String SYMBOLS = "0123456789";
    private static final Random RANDOM = new SecureRandom();
    
    public static String getNonce_str() {
		// 如果需要4位,那 new char[4] 即可,其他位数同理可得
		char[] nonceChars = new char[4];
		for (int index = 0; index < nonceChars.length; ++index) {
			nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
		}
		return new String(nonceChars);
	}
    
    //2.发送短信
    public static String sendCode(String phone){
        String result =null;
        String url ="http://v.juhe.cn/sms/send";//请求接口地址
        String code=getNonce_str();
        Map params = new HashMap();//请求参数
            params.put("mobile",phone);//接收短信的手机号码
            params.put("tpl_id",123456);//短信模板ID,请参考个人中心短信模板设置
            params.put("tpl_value","#code#="+code);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号,请先分别进行urlencode编码后再传递,<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("dtype","json");//返回数据的格式,xml或json,默认json
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                return code;
            }else{
                return null;
            }
        } catch (Exception e) {
        	return null;
        }
    }
 
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
    	sendCode("***");
	}
    
}



评论区
请写下您的评论...
暂无评论...
猜你喜欢
其他 1683 首先你有一个网站和一个域名首先在中搜索ssl,点击SSL书到控制台控制台购买完成后点击书申请,会让你填写认息提交完成后会有一个CA审核的状态,不过审核过程应该很快。审核完成后然后点击下
工具 2069 javaweb图片1.的作用:防止恶意破解密、刷票、论坛灌水、刷页。有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上使用是现在很多网站通行的方
工具 2327 esc服务器为了安全默认禁用25端,所以会导致JavaMail发送邮件失败。错误代
前端,java基础 1507 一、pom依赖二、后端示例三、前端页面  有些场景需要生成带参的小程序二维,比如商城为每个商品生成小程序二维,通过微跳转到该商品所在的展示页面。微为开发者们提供了相应
工具 1596 java正则表达式同时手机号或电话号importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassPhone
spring/springmvc 4061 我在之前进行开发的时候经常会有大量的参,而我一般的操作方法就是在controller中进行参的校,这样并没有什么错,但是代略显臃肿,而使用springboot的@vaild注解可以减
java 1333 巴巴Java开发手册-终极版.pdf
工具 1790 packagecom.dzqc.dz.main.util;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/***
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。