java手机验证码实现

1\网易云信 实现 免费20条测试

   到https://app.netease.im 注册一个帐号

   完成后进入控制台>>自己创建的应用>>申请短信模块>>短信模板管理 >>创建模板>>等待审核通过>>审核通过后把 模板ID 放到下面代码中的templateid=

 

 
 

 

package com.gkzy.core.util;

import java.io.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;

public class Msm {

    public static void main(String[] args) throws Exception
    {
        //System.out.println(sendMsg("1234"));

    }
    /**
     * 发送POST方法的请求
     * 
     * @return 所代表远程资源的响应结果
     */
    public String sendMsg(String phone,String code)//phone手机号码,code验证码
    {
        String appKey = "0e........94";
        String appSecret = "3e......0e2";
        String nonce = "baoluo"; // 随机数(最大长度128个字符)
        String curTime = String.valueOf((new Date()).getTime() / 1000L); // 当前UTC时间戳
        System.out.println("curTime: " + curTime);


        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        System.out.println("checkSum: " + checkSum);
        
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try
        {
            String url = "https://api.netease.im/sms/sendtemplate.action"; //网址可以不修改
            String encStr1 = URLEncoder.encode(code, "utf-8");
            String encStr2 = URLEncoder.encode("name", "utf-8"); // url编码;防止不识别中文
            String params = "templateid=3051232&mobiles=[\""+phone+"\"]" 
                            + "&params=" + "[\"" + encStr1 + "\",\""+ encStr2 + "\"]";
            System.out.println("params:" + params);


            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("AppKey", appKey);
            conn.setRequestProperty("CheckSum", checkSum);
            conn.setRequestProperty("CurTime", curTime);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            conn.setRequestProperty("Nonce", nonce);


            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
     


            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            System.out.println(conn);
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            System.out.println("in"+in);
            String line;
            while ((line = in.readLine()) != null)
            {
                result += line;
            }
        } catch (Exception e)
        {
            System.out.println("发送 POST 请求出现异常!\n" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
}
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' };
}

 

2.网建 实现 免费5条测试

 注册地址:http://www.smschinese.cn/     

 

package com.gkzy.core.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class MsmCode {

    public String sendCode(String phone,String conten,String code)throws Exception{
       System.out.println("::::::::::::"+code);
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn"); 
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
        NameValuePair[] data ={ new NameValuePair("Uid", "用户名"),
                new NameValuePair("Key", "8......7"),
                new NameValuePair("smsMob",phone),
                new NameValuePair("smsText","发送内容")};
        post.setRequestBody(data);
       
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:"+statusCode);
        for(Header h : headers)
        {
        System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk")); 
        System.out.println(result); //打印返回消息状态
        post.releaseConnection();
        return result;
    }
}

 

 

转载于:https://www.cnblogs.com/lujion/p/6596493.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值