java发送短信验证码的功能实现

总结一下发送短信验证码的功能实现

(题外话:LZ是在腾讯云买的第三方(山东鼎信)短信服务平台的接口,1块钱20次的套餐来练手,哈哈,给他们打个广告,有需要的可以去购买哈,下面是购买链接短信服务平台购买链接哦

 

1.新建一个maven项目

 

 

2.pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>message</name>
    <groupId>com.cyf</groupId>
    <artifactId>message</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
                    </webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

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

</project>

 

3.SmsTest.java

package com;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 短信发送实例
 * java项目需要jdk1.7及以上版本,需要引用httpClient4.2.4及以上版本
 * 该实例为maven项目,引用httpClient4.2.4可使用pom.xml直接引用
 *
 * @author txy
 * @date 2018/01/30.
 */
public class SmsTest {
    /**
     * 腾讯云交易id
     * 必填项
     */
    private static String SECRET_ID = "";
    /**
     * 腾讯云交易key
     * 必填项
     */
    private static String SECRET_KEY = "";


    public static void main(String[] args) throws Exception {
        /**
         * api发送接口
         * 必填项
         */
        String host = "http://service-4xrmju6b-1255399658.ap-beijing.apigateway.myqcloud.com";
        String path = "/release/dxsms";
        /**
         * 您需要发送手机号
         * 必填项
         */
        String mobile = "176********";
        /**
         * 模板id,联系客服申请通过的模板,
         * 例:TP1801042是已申请好的模板:您的验证码是#code#
         * 必填项
         */
        String tpl_id = "TP1801042";
        /**
         * 与模板中对应的变量,有多个变量则使用","隔开
         * 例:短信模板为“您的电话#telephone#成功缴费#money#元,如未到账可直接拨打客服电话#phone#”,
         * 则param="telephone:13288888888,money:100,phone:400-888888"
         *
         */
        String param = "code:1234";
        String url = host + path + "?mobile=" + mobile + "&tpl_id=" + tpl_id + "&param=" + param;
        /**
         * httpClient4.2.4及以上版本
         */
        HttpClient httpClient = new DefaultHttpClient();
        // get method
        HttpGet httpGet = new HttpGet(url);
        Date date = new Date();
        httpGet.setHeader("Date", gmtTIME(date));
        String timeStr = "date: " + gmtTIME(date);
        String sign = hmacSHA1Encrypt(timeStr, SECRET_KEY);
        String authStr = "hmac id=\"" + SECRET_ID + "\",algorithm=\"hmac-sha1\",headers=\"date\", signature=\"" + sign + "\"";
        httpGet.addHeader("Authorization", authStr);
        //response
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
        } catch (Exception e) {
        }
        //get response into String
        String temp = "";
        try {
            HttpEntity entity = response.getEntity();
            temp = EntityUtils.toString(entity, "UTF-8");
            //输出返回值
            System.out.println(temp);
        } catch (Exception e) {
        }


    }

    /**
     * HmacSHA1加密
     *
     * @param encryptText 加密字符串
     * @param encryptKey  加密key
     * @return
     * @throws Exception
     */
    private static String hmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes("UTF-8");
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes("UTF-8");
        //完成 Mac 操作,base64编码
        String sign = Base64.encodeBase64String(mac.doFinal(text));
        return sign;
    }


    /**
     * 获得格林威治时间
     *
     * @param date 时间
     * @return
     */
    private static String gmtTIME(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        // 设置时区为GMT
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String time = sdf.format(date.getTime());
        return time;
    }

}

 4.完成

转载于:https://www.cnblogs.com/feifeicui/p/8573390.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现手机短信验证码平台可以使用第三方短信平台接口来发送短信验证码。以下是实现步骤: 1. 注册第三方短信平台账号,并获取API接口信息。 2. 在Java项目中引入第三方短信平台的SDK(软件开发工具包)。 3. 编写Java代码,调用SDK提供的接口,传递短信内容和手机号码,发送短信验证码。 以下是一个简单的Java发送短信验证码的示例代码: ```java // 引入第三方短信平台SDK import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.models.*; import com.aliyun.teaopenapi.models.Config; public class SmsUtil { // 设置API接口信息 private static final String accessKeyId = "yourAccessKeyId"; private static final String accessKeySecret = "yourAccessKeySecret"; private static final String signName = "yourSignName"; private static final String templateCode = "yourTemplateCode"; public static void sendSms(String mobile, String code) throws Exception { // 创建配置对象 Config config = new Config() .setAccessKeyId(accessKeyId) .setAccessKeySecret(accessKeySecret); // 创建Client对象 Client client = new Client(config); // 创建发送短信请求对象 SendSmsRequest sendSmsRequest = new SendSmsRequest() .setPhoneNumbers(mobile) .setSignName(signName) .setTemplateCode(templateCode) .setTemplateParam("{\"code\":\"" + code + "\"}"); // 发送短信 SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest); System.out.println(sendSmsResponse.getBody()); } } ``` 在上述代码中,我们使用了阿里云短信平台提供的SDK来实现发送短信验证码功能。需要事先在阿里云短信平台注册账号,并获取相应的API接口信息。然后,我们通过创建Config对象来设置API接口信息,并使用Client对象来发送短信。在发送短信时,需要设置手机号码、短信签名、短信模板ID和短信模板参数等信息。最后,我们将发送短信的结果输出到控制台。 以上就是基于Java实现手机短信验证码平台的简单示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值