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.完成


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM