Java implementation uses the third party platform to send SMS authentication code _JAVA

Source: Internet
Author: User

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

This paper takes the registration as an example to complete the function of the SMS Verification Code on the basis of the Springmvc+spring+mybatis framework.

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

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

The general third party SMS platform will have their own SMS interface, as long as the understanding of their interface for a little change to meet their needs.

First 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

Import java.io.UnsupportedEncodingException;
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 Sendmsg_webchinese {public static void main (string[] args) throws Exception {httpclient client = new HTTPCLI
ENT (); Postmethod post = new Postmethod ("http://gbk.sms.webchinese.cn");
The third party SMS Service address Post.addrequestheader ("Content-type", "APPLICATION/X-WWW-FORM-URLENCODED;CHARSET=GBK");//Set transcoding in header file namevaluepair[] Data ={new Namevaluepair ("Uid", "Site user name"), New Namevaluepair ("Key", "Interface Security secret Key"), New Namevaluepair ("Smsmob
"," mobile phone number "), New Namevaluepair (" Smstext "," Verification Code: 8888 ")};
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);
Print return message status post.releaseconnection (); }
}

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

The interface also has a result information, its role is to tell users the status of sending text messages, 1 to send success, others less than 0 for failure, here as long as you know 1 is successful.

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

Import Java.util.HashMap;
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;
Import Com.yuetile.utils.VerifyingCodeGenerator; public class Sendmsg_webchinesecontroller {public static hashmap<string,string> Getmessagestatus (String phone)
Throws exception{hashmap<string,string> m=new hashmap<string,string> ();
HttpClient client = new HttpClient (); 
Postmethod post = new Postmethod ("http://gbk.sms.webchinese.cn"); Post.addrequestheader ("Content-type", "APPLICATION/X-WWW-FORM-URLENCODED;CHARSET=GBK");//Set the transcoding String in the header file code= Verifyingcodegenerator.generate ()//Verify code namevaluepair[] Data ={new Namevaluepair ("Uid", "* * *"), New Namevaluepair (" Key "," "Hu"), New Namevaluepair ("Smsmob", phone), New Namevaluepair ("Smstext", "You are registering this website member, this time the authentication code is:" +code+ "" + "
Valid time is 5 minutes ")};
M.put ("code", code);
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);
Print return message status M.put ("result", result);
Post.releaseconnection ();
return m; }
}

Represents the account password that is registered on the third party platform.

Action Layer:

/** * @author Hang * @Decription registration, send SMS authentication code, save to session * @param encapsulate client Request POST * @return Return Status parameter * @throws Exception * Responsebody @RequestMapping (value = UrlDefine.Register.CHECKMESSAGEWORK, method = requestmethod.post) public Object
Sendcheckmessage (httpservletrequest request, @RequestBody UserBean u) throws Exception {String message = "Send Success"; String Phone=u.gettelephone ();
Get the phone number sent to the client UserBean user = Userservice.getbyphone (phone); if (user!= null) {message = "The mobile number has been registered"; return new Response (status.error, message);} else {hashmap<string, STRING&G T m = sendmsg_webchinesecontroller.getmessagestatus (phone);    Application sends SMS interface String result = M.get ("result");   Gets the result value if (Result.trim (). Equals ("1")) {//if 1, which means that String code = m.get ("code") is sent successfully;  Gets the content of the authenticated code sent Logger.info ("The Authentication Code sent:" +code); Print Log HttpSession session = Request.getsession ();    Set Session Session.setattribute ("code", code); To save the Session.setmaxinactiveinterval (60 * 5) by storing the SMS verification in the session;//save time temporarily set to 5 minutes return NEW Response (status.success, message);
else {message = "SMS Send Failed"; return new Response (status.error, messages);} }

This will be able to send a successful.

Test:

Use Postman to test locally:

Results:

Sent to this success.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.