Java realizes the whole process of mobile phone message verification

Source: Internet
Author: User

SMS verification is now in a variety of systems can be said to be very common, this may be convenient and security considerations, so it is widely used, this article to a text message interface example, to explain how to use the SMS interface.

First, pre-work

First, we need to select an SMS interface company, then go to register and get a series of IDs, etc., and then we can formally create our SMS business. The following is an example of an SMS interface to explain.

1.1. Registration

Http://www.miaodiyun.com/index.html (This is an example of which platform to look at personally)

1.2. Get the account SID and Auth TOKEN

1.3. Create SMS Template

For example, click Configuration Management , then go to the SMS template , then click New Template , create your text message template .

My template is given below as a reference.

Note: the information on the SMS template created above needs to be in code and must be consistent, otherwise an exception will occur.

For example, the text message template above should be: "" Ouyang Technology Login Verification code: {1}, such as non-operation, please ignore this text message. ", {1} as a placeholder, is your SMS verification code.

Well, with these preparations, you can start texting.

Second, the specific code

Config.java:
This class is mainly the configuration information for some of the frequently-lit parameters.

Here we need to modify the and that we get when we register ACCOUNT SID AUTH TOKEN .

/** * 系统常量 */public class Config{    /**     * url前半部分     */    public static final String BASE_URL = "https://api.miaodiyun.com/20150822";    /**     * 开发者注册后系统自动生成的账号,可在官网登录后查看     */    public static final String ACCOUNT_SID = "aac6e373c7534007bf47648ba34ba2f1";    /**     * 开发者注册后系统自动生成的TOKEN,可在官网登录后查看     */    public static final String AUTH_TOKEN = "47605360a97a4f81bcd576e8e0645edf";    /**     * 响应数据类型, JSON或XML     */    public static final String RESP_DATA_TYPE = "json";}

Httputil.java (HTTP request tool):

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.net.url;import Java.net.urlconnection;import Java.text.SimpleDateFormat;     Import Java.util.date;import org.apache.commons.codec.digest.digestutils;/** * HTTP request tool */public class HttpUtil{/** * Constructs common parameters timestamp, sig, and Respdatatype * * @return * */public static String Createcommonparam () {/        /timestamp SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss");        String timestamp = Sdf.format (new Date ());        Signature String sig = Digestutils.md5hex (Config.account_sid + config.auth_token + timestamp);    Return "&timestamp=" + timestamp + "&sig=" + sig + "&respdatatype=" + config.resp_data_type; }/** * POST request * * @param URL * Function and operation * @param body * data to post * @re Turn * @throws IOException */public static string post (string URL, STring body) {System.out.println ("URL:" + system.lineseparator () + URL);        System.out.println ("Body:" + system.lineseparator () + body);        String result = "";            try {outputstreamwriter out = null;            BufferedReader in = null;            URL realurl = new URL (URL);            URLConnection conn = Realurl.openconnection ();            Set connection parameter Conn.setdooutput (TRUE);            Conn.setdoinput (TRUE);            Conn.setconnecttimeout (5000);            Conn.setreadtimeout (20000);            Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");            Submit data out = new OutputStreamWriter (Conn.getoutputstream (), "UTF-8");            Out.write (body);            Out.flush ();            Read return data in = new BufferedReader (New InputStreamReader (Conn.getinputstream (), "UTF-8"));            String line = ""; Boolean firstline = true; Read the first line without a newline character while (lines = In.reAdline ()) = null) {if (firstline) {firstline = false;                } else {result + = System.lineseparator ();            } result + = line;        }} catch (Exception e) {e.printstacktrace ();    } return result; }/** * Callback Test Tool method * * @param URL * @param reqstr * @return */public static String Posthuidi        AO (string url, String body) {string result = "";            try {outputstreamwriter out = null;            BufferedReader in = null;            URL realurl = new URL (URL);            URLConnection conn = Realurl.openconnection ();            Set connection parameter Conn.setdooutput (TRUE);            Conn.setdoinput (TRUE);            Conn.setconnecttimeout (5000);            Conn.setreadtimeout (20000); Submit data out = new OutputStreamWriter (Conn.getoutputstreaM (), "UTF-8");            Out.write (body);            Out.flush ();            Read return data in = new BufferedReader (New InputStreamReader (Conn.getinputstream (), "UTF-8"));            String line = ""; Boolean firstline = true;                     Read the first line without a newline character (line = In.readline ()) = null) {if (firstline) {                Firstline = false;                } else {result + = System.lineseparator ();            } result + = line;        }} catch (Exception e) {e.printstacktrace ();    } return result; }}

Verification Code Notification SMS interface: (most important)
We need to modify the information we obtained at the time of registration.

    • Modify Smscontent
      Change the text message to the text message template you created.
      Note: Be sure to stay consistent.
      import java.net.URLEncoder;

Import Com.miaodiyun.httpApiDemo.common.Config;
Import Com.miaodiyun.httpApiDemo.common.HttpUtil;

/**

  • Verification Code Notification SMS interface
  • @ClassName: Industrysms
  • @Description: Verification Code Notification SMS interface
  • */
    public class Industrysms
    {
    private static String operation = "/industrysms/sendsms";

    private static String Accountsid = Config.account_sid;
    private static String to = "13767441759";

    private static String code = Smscode ();
    Login Verification Code: {1}, please ignore this text message if you do not.
    private static String smscontent = "Ouyang Technology" Login Verification Code: "+code+", such as non-operation, please ignore this text message. ";

    /**

      • Verification Code Notification SMS
        */
        public static void Execute ()
        {
        String tmpsmscontent = null;
        try{
        Tmpsmscontent = Urlencoder.encode (smscontent, "UTF-8");
        }catch (Exception e) {

        }
        String url = config.base_url + operation;
        String BODY = "accountsid=" + accountsid + "&to=" + to + "&smscontent=" + tmpsmscontent

        • Httputil.createcommonparam ();

        Submit Request
        String result = httputil.post (URL, body);
        SYSTEM.OUT.PRINTLN ("Result:" + system.lineseparator () + result);
        }

    Create a verification code
    public static String Smscode () {
    String random= (int) ((Math.random ()9+1)100000) + "";
    System.out.println ("Verification Code:" +random);
    return random;
    }
    }

上面这些是主要的类,还有其他的类在文章末尾给出源代码。### 三、手机短信验证测试

public class Test
{

/** * @param args */public static void main(String[] args){    // 验证码通知短信接口     IndustrySMS.execute();}

}

##### 源代码下载https://download.csdn.net/download/sihai12345/10472391>文章有不当之处,欢迎指正,如果喜欢阅读,你也可以关注我的公众号:`好好学java`,获取优质学习资源。

Java realizes the whole process of mobile phone message verification

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.