In a small project I did some time ago, it involved logging in and registering with SMS verification codes. I had never covered this before. I actually didn’t understand it after reading other people’s blogs. Now I will write down the function of using the third-party SMS platform to send verification codes.
Taking registration as an example, this article completes the SMS verification code function based on the SpringMVC+Spring+Mybatis framework.
The principle of sending SMS verification code is: randomly generate a 6-digit number, save the 6-digit number into the session, the client judges the corresponding session through sessionid, and compares the verification code entered by the user with the verification code recorded by the session.
In order to prevent any ads from being suspected, I will not talk about which SMS platform is.
Generally, third-party SMS platforms will have their own SMS interface. As long as you understand their interface and make a slight change, you can meet your needs.
First, list the SMS platform interface code: here we need to download three jar packages 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"); //The third-party SMS service address post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk"); //Set transcoding NameValuePair[] data ={ new NameValuePair("Uid", "user name of this site"),new NameValuePair("Key", "interface security key"),new NameValuePair("smsMob","mobile 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 that the information we want to send is in this line of code: NameValuePair[] data ={ new NameValuePair("Uid", "Site Username"), new NameValuePair("Key", "Interface Security Key"), new NameValuePair("smsMob", "Mobile phone number"), new NameValuePair("smsText","Verification code: 8888")};
There is also a result message in this interface, which is used to tell the user the status of sending SMS. 1 means the sending is successful, and others less than 0 are failures. Here, just know that 1 is successful.
In our actual operations, the verification code must be generated by us. Get the result information together with the verification code, so it is easy to think of using a HashMap collection. Here are the changes to the interface based on 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 transcoding in the header file String code=VerifyingCodeGenerator.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+""+"ValueTime 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;}}*** means the account password registered on a third-party platform.
ACTION layer:
/*** @author hang * @Deccription Register, send SMS verification 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 successfully";String phone=u.getTelephone(); //Get the mobile phone number sent by the client UserBean user = userService.getByPhone(phone); if (user != null) {message = "The mobile phone number has been registered"; return new Response(Status.ERROR, message);} else {HashMap<String, String> m = SendMsg_webchineseController.getMessageStatus(phone); //Application SMS interface String result = m.get("result"); //Get result if (result.trim().equals("1")) { //If it is 1, it means that the String code is successfully sent. //Get the sent verification code content logger.info("sent verification code:"+code); //Print the log HttpSession session = request.getSession(); //Set sessionssion.setAttribute("code", code); //Put the SMS verification code in the session to save session.setMaxInactiveInterval(60 * 5); //Save time temporarily set to 5 minutes return new Response(Status.SUCCESS, message);} else {message = "SMS sending failed"; return new Response(Status.ERROR, message);}}}This way, the sending will be successful.
test:
Test locally using POSTMAN:
result:
Send successfully here.
The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!