Ssm implemented in the SMS verification code

The test uses a http://www.webchinese.com.cn/default.shtml platform service, code reference the https://blog.csdn.net/qq_33165600/article/details/79506936 .

First, download the required jar package: commons-logging-1.1.1.jar, commons-httpclient-3.1.jar, commons-codec-1.4.jar.

Get registered a good account, write down their own accounts and key (not password).

SMS signature is part of the beginning [bracketed].

Send message to generate the class code verification means:

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

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

public class SendMessage {
    public static void main(String[] args) throws Exception{
        SendMessage sendMessage = new SendMessage();
        sendMessage.getMessageStatus ( "your phone number" );
    }
    public HashMap<String,String> getMessageStatus(String phone) throws HttpException, IOException {
        The HashMap <String, String> m = new new the HashMap <String, String> ();
         // HTTP protocol 
        HttpClient Client = new new HttpClient ();
         // connecting third-party platform 
        a PostMethod = POST new new a PostMethod ( "HTTP: //gbk.api .smschinese.cn / " );
        post.addRequestHeader ( "the Content-the Type", "file application / X-WWW-form-urlencoded; charset = GBK"); // disposed in the header file transcoding


        // generates six codes 
        String o charValue = "" ;
         for ( int I = 0; I <. 6; I ++ ) {
             char C = ( char ) (randomInt (0,. 9) + '0' );
            charValue += String.valueOf(c);
        }
        // SMS templates 
        of NameValuePairs [] Data = {
                 new new of NameValuePairs ( "Uid", "scxdhr"), // SMS-messaging user name registered 
                new new of NameValuePairs ( "Key", "d41d8cd98f00b204e980"), // key 
                new new of NameValuePairs ( "smsMob", phone), // the phone number you want to send 
                new new NameValuePair ( "smsText", "your verification code is:" + charValue) // content of messages 
        };

        post.setRequestBody(data);
        client.executeMethod(post);
        //获取http头
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();

        System.out.println("statusCode:"+statusCode);

        for(Header h:headers){
            System.out.println(h.toString());
        }
        // Get the return message 
        String Result = new new String (post.getResponseBodyAsString () the getBytes ( "GBK." ));
        System.out.println (Result); // print the status message returned
         // returns the message and placed in a 6-digit codes list which m 
        m.put ( "Result" , Result);
        m.put ( "code" , charValue);
         // Disconnect from third-party platforms 
        post.releaseConnection ();

        return m;

    }
    // generates codes 
    public  static  int randomInt ( int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }
}

 

return result "1", says sent successfully, will receive a text message on your phone.

 

There are three ways to get the phone verification code in the background:

 

1. setAttribute method using the session, the stored data to the page buffer, but then closed, it stores the verification code will fail, it is not recommended to use this method.

 

2. Use redis database cache validation code, redis database used for this fit is very high, also set the cache expiration time, write up is very simple.

 

3. Write a tool class CacheUtil, with a cache map, the failure time data can be provided, the following paste the code:

import java.util.Map;
import java.util.concurrent.*;

/**
 * Cache Tools
 *
 * @author lance
 * @since 2018-10-25
 */
public class CacheUtil
{
    /**
     * Storage of data to be cached map
     */
    private final static Map<String, Entity> MAP = new ConcurrentHashMap<>();
    /**
     * Timer thread pool, to clear the cache expires
     */
    private final static ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor();

    /**
     * Adding a Cache
     *
     * Param key de key map
     * @param data map的value
     */
    public synchronized static void put(String key, Object data)
    {
        CacheUtil.put(key, data, 0);
    }

    /**
     * Adding a Cache
     *
     * Param key de key map
     * @param data   map的value
     * @Param The expire time expires, unit: ms, 0 indicates an infinite length
      * / 
    public  the synchronized  static  void PUT (String Key, Object Data, Long The expire)
    {
        // Clear the original the Map 
        CacheUtil.remove (Key);
         // set the expiration time 
        IF (The expire> 0 )
        {
            Future future = EXECUTOR.schedule(() ->
            {
                // expire cleared the Map 
                the synchronized (CacheUtil. Class )
                {
                    MAP.remove(key);
                }
            }, expire, TimeUnit.MILLISECONDS);
            MAP.put(key, new Entity(data, future));
        }
        else
        {
            // not set the expiration time 
            map.put (Key, new new the Entity (Data, null ));
        }
    }

    /**
     * Check whether there are key cache
     *
     * Param key de key map
     * @return 是否存在key
     */
    public synchronized static boolean keyExists(String key)
    {
        return MAP.get(key) != null;
    }

    /**
     * Read cache
     *
     * Param key de key map
     * @return map的value
     */
    public synchronized static Object get(String key)
    {
        Entity entity = MAP.get(key);
        return entity == null ? null : entity.getValue();
    }

    /**
     * Read cache
     *
     * Param key jian
     * @Param CLS value type
     * @Return Map value stored in the object
      * / 
    public  the synchronized  static <T> T GET (String Key, Class <T> CLS)
    {
        return cls.cast(CacheUtil.get(key));
    }

    /**
     * clear cache
     *
     * Param key de key map
     * @return
     */
    public synchronized static void remove(String key)
    {
        // clear the original data cache 
        the Entity Entity = MAP.remove (Key);

        // Clear the original map timers 
        IF ( null ! = The Entity)
        {
            Future future = entity.getFuture();
            if (future != null)
            {
                future.cancel(true);
            }
        }
    }

    /**
     * Cache entity class
     */
    private static class Entity
    {
        /**
         * Map value
         */
        private Object value;
        /**
         * Timer
         */
        private Future future;

        private Entity(Object value, Future future)
        {
            this.value = value;
            this.future = future;
        }

        /**
         * Get the map value
         *
         * @return map值
         */
        public Object getValue()
        {
            return value;
        }

        /**
         * Get Future object
         *
         * @return Future对象
         */
        private Future getFuture()
        {
            return future;
        }
    }
}

 

The rest is sent from the front desk check mobile phones and verification code are the same, not repeat them.

Guess you like

Origin www.cnblogs.com/scxblogs/p/11906144.html