Java uses third-party platforms to send SMS verification codes.

Source: Internet
Author: User

Some time ago to do a small project, involving the use of SMS Verification code login, registration issues, not previously involved in this piece, looked at other people's blog is actually indefinitely, and now will do their own use of third-party SMS platform to send verification code this function to write down.

In this paper, the registration as an example, based on the Springmvc+spring+mybatis framework to complete the SMS Verification code function.

The principle of sending SMS verification code is: randomly generate a 6-digit number, the 6-digit number is saved to the session, the client through the SessionID to determine the corresponding session, the user input verification code and the session record of the verification code comparison.

In order to prevent advertising suspicion here is not to say that the message platform is which.

The general third-party SMS platform will have their own SMS interface, as long as they understand their interface to make a slight change to meet their own needs.

First of all, the SMS Platform Interface code is listed: here to download three jar package Commons-logging-1.1.1.jar,commons-httpclient-3.1.jar,commons-codec-1.4.jar

Importjava.io.UnsupportedEncodingException;ImportOrg.apache.commons.httpclient.Header;Importorg.apache.commons.httpclient.HttpClient;ImportOrg.apache.commons.httpclient.NameValuePair;ImportOrg.apache.commons.httpclient.methods.PostMethod; Public classSendmsg_webchinese { Public Static voidMain (string[] args)throwsexception{httpclient Client=NewHttpClient (); Postmethod Post=NewPostmethod ("http://gbk.sms.webchinese.cn");//The third-party SMS service addressPost.addrequestheader ("Content-type", "APPLICATION/X-WWW-FORM-URLENCODED;CHARSET=GBK");//set transcoding in the header filenamevaluepair[] Data ={NewNamevaluepair ("Uid", "Site user name"),NewNamevaluepair ("Key", "Interface security key"),NewNamevaluepair ("Smsmob", "mobile number"),NewNamevaluepair ("Smstext", "CAPTCHA: 8888")};p ost.setrequestbody (data); Client.executemethod (POST); Header[] Headers=post.getresponseheaders ();intStatusCode =Post.getstatuscode (); System.out.println ("StatusCode:" +statusCode); for(Header h:headers) {System.out.println (h.tostring ());} String result=NewString (Post.getresponsebodyasstring (). GetBytes ("GBK")); SYSTEM.OUT.PRINTLN (result); //print return message statuspost.releaseconnection ();}}

It is not difficult to see that the information we want to send is in this line of code: namevaluepair[] Data ={new Namevaluepair ("Uid", "Site user name"), New Namevaluepair ("Key", "Interface security key"), New Namevaluepair ("Smsmob", "mobile number"), New Namevaluepair ("Smstext", "CAPTCHA: 8888")};

The interface also has a result information, its role is to tell the user the status of the message sent, 1 to send the success, the other less than 0 for the failure, as long as it knows that 1 is successful.

In our actual operation, the verification code must be generated by ourselves. The result information is obtained with the verification code, so it is easy to think of a HashMap collection. Here are the changes to the interface in the project's own requirements:

ImportJava.util.HashMap;ImportOrg.apache.commons.httpclient.Header;Importorg.apache.commons.httpclient.HttpClient;ImportOrg.apache.commons.httpclient.NameValuePair;ImportOrg.apache.commons.httpclient.methods.PostMethod;ImportCom.yuetile.utils.VerifyingCodeGenerator; Public classSendmsg_webchinesecontroller { Public StaticHashmap<string,string> getmessagestatus (String phone)throwsException{hashmap<String,String> m=NewHashmap<string,string>(); HttpClient Client=NewHttpClient (); Postmethod Post=NewPostmethod ("http://gbk.sms.webchinese.cn"); Post.addrequestheader ("Content-type", "APPLICATION/X-WWW-FORM-URLENCODED;CHARSET=GBK");//set transcoding in the header fileString code=verifyingcodegenerator.generate ();//Verification Codenamevaluepair[] Data ={NewNamevaluepair ("Uid", "* * *"),NewNamevaluepair ("Key", "******"),NewNamevaluepair ("Smsmob", phone),NewNamevaluepair ("Smstext", "You are registering for this site member, this code is:" +code+ "" + "valid time is 5 minutes")};m.put ("Code", code);p ost.setrequestbody (data); Client.executemethod (POST); Header[] Headers=post.getresponseheaders ();intStatusCode =Post.getstatuscode (); System.out.println ("StatusCode:" +statusCode); for(Header h:headers) {System.out.println (h.tostring ());} String result=NewString (Post.getresponsebodyasstring (). GetBytes ("GBK")); SYSTEM.OUT.PRINTLN (result); //print return message statusM.put ("Result", result);p ost.releaseconnection ();returnm;}}

Represents the password of the account registered on the third party platform.

Action Layer:

/*** @authorHang * @Decription registration, send SMS verification code, save to session *@paramencapsulate Client Request POST *@returnreturn Status parameter *@throwsException*/@ResponseBody @requestmapping (value= UrlDefine.Register.CHECKMESSAGEWORK, method =requestmethod.post) PublicObject sendcheckmessage (httpservletrequest request, @RequestBody UserBean u)throwsException {String message= "Sent successfully"; String Phone=u.gettelephone ();//get the phone number sent to the clientUserBean user =Userservice.getbyphone (phone);if(User! =NULL) {Message= "The mobile number has been registered";return NewResponse (status.error, message);} Else{HashMap<string, string> m = sendmsg_webchinesecontroller.getmessagestatus (phone);//app Send SMS interfaceString result = M.get ("result");//Gets the result valueif(Result.trim (). Equals ("1")) {//if 1, indicates a successful sendString code = m.get ("code");//get the verification code content sentLogger.info ("Sent Verification code:" +code);//Print LogHttpSession session = Request.getsession ();//Set SessionSession.setattribute ("code", code);//Save SMS Verification to sessionSession.setmaxinactiveinterval (60 * 5);//save time temporarily set to 5 minutesreturn NewResponse (status.success, message);} Else{message= "SMS Send Failed";return NewResponse (status.error, message); }}}

This will send you a success.

Test:

Use Postman to test locally:

Results:

Successfully sent to this.

Java uses third-party platforms to send SMS verification codes.

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.