JAVA uses a third-party platform to send text message verification codes ., Send SMS in java

Source: Internet
Author: User

JAVA uses a third-party platform to send text message verification codes ., Send SMS in java

In a small project that I did some time ago, I encountered the problem of using text message verification codes to log on and register. I have not mentioned this one before. I can understand others' blogs, now, let's take a note of our function of sending verification codes using a third-party SMS platform.

This article takes registration as an example to complete the text message verification code function based on the SpringMVC + Spring + Mybatis framework.

The principle of sending the SMS verification code is: randomly generate a six-digit number and save the six-digit number to the session. The client judges the corresponding session through the sessionid, the verification code entered by the user is compared with the verification code recorded by the session.

To prevent advertising suspicion, we will not mention the text message platform.

Generally, third-party text messaging platforms have their own SMS interfaces. You only need to understand their interfaces and make slight changes to meet your needs.

First list the SMS platform interface code: 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 HttpClient (); PostMethod post = new PostMethod ("http://gbk.sms.webchinese.cn "); // This third-party text message service address post. addRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = gbk "); // set transcoding NameValuePair [] data = {new NameValuePair ("Uid", ""), new NameValuePair ("Key", "") in the header file "), new NameValuePair ("smsMob", "mobile phone number"), new NameValuePair ("smsText", "Verification Code: 8888" )};post.setRequestBody(data);client.exe cuteMethod (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 the returned message status post. releaseConnection ();}}

 

It is easy to see that the information we want to send is in this line of code: NameValuePair [] data = {new NameValuePair ("Uid", "User Name"), new NameValuePair ("Key ", "API security key"), new NameValuePair ("smsMob", "mobile phone number"), new NameValuePair ("smsText", "Verification Code: 8888 ")};

This interface also has a result information, which is used to tell the user the status of text message sending. 1 indicates that the message is sent successfully, and other messages smaller than 0 are failed. Here, you only need to know that 1 is successful.

In our actual operation, the verification code must be generated by ourselves. The result information is obtained together with the verification code, so it is easy to use a HashMap set. The following is an interface change as required by the project:

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 post method ("http://gbk.sms.webchinese.cn"); post. addRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = gbk"); // set transcoding String code = VerifyingCodeGenerator in the header file. generate (); // Verification Code NameValuePair [] data = {new NameValuePair ("Uid", "***"), new NameValuePair ("Key ", "******"), new NameValuePair ("smsMob", phone), new NameValuePair ("smsText", "You are registering a member of this site. This verification code is: "+ code +" "+" Valid time: 5 minutes ")}; m. put ("code", code==post.setrequestbody(data=;client.exe cuteMethod (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 the returned message status m. put ("result", result); post. releaseConnection (); return m ;}}

 

* ** Indicates the account and password registered on a third-party platform.

ACTION layer:

/*** @ Author hang * @ Decription registration, send the SMS verification code, save to Session * @ param encapsulate client request POST * @ 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 = "sent successfully"; String phone = u. getTelephone (); // get the mobile phone number UserBean user = sent from the client UserService. getByPhone (phone); if (user! = Null) {message = "this phone number has been registered"; return new Response (Status. ERROR, message) ;}else {HashMap <String, String> m = SendMsg_webchineseController.getMessageStatus (phone); // The application sends the SMS interface String result = m. get ("result"); // get the result value if (result. trim (). equals ("1") {// if it is 1, the String code = m is successfully sent. get ("code"); // get the content of the sent Verification code logger.info ("sent Verification code:" + code); // print the log HttpSession session = request. getSession (); // set sessionsession. setAttribute ("code", code); // put the SMS verification code into the session to save the session. setMaxInactiveInterval (60*5); // the storage time is set to 5 minutes. return new Response (Status. SUCCESS, message);} else {message = "failed to send SMS"; return new Response (Status. ERROR, message );}}}

 

In this way, the message can be sent successfully.

Test:

Use POSTMAN for local testing:

Result:

The message is sent successfully.

 

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.