Hello friends, welcome to the new tutorial. In this tutorial, we will learn How to Generate OTP and Send to Mobile in Java. For Generating OTP, we will use the Random class of Java to generate a Random number and send it to any specific mobile number, we will use the BulkSMS API.
Let’s start our tutorial and learn step by step how to Generate OTP and Send to Mobile in Java.
How to Generate OTP and Send to Mobile in Java
Register an Account with BulkSMS
- So the first thing you need to do is Register an account with the BulkSMS to use their API.
- Visit the website BulkSMS.com, and at the top right corner, you will see a button for Sign Up Today. Click on that to start the Registration process.
- After that, you need to enter your Email Address and click on the Send Code Button to proceed.
- You will get a verification code in your email. You need to copy and paste your code and then click on the Check code button.
- If the code is correct, you will be redirected to the following page, where you have to fill in the necessary details and click on the submit button.
- You need to remember your username and password because they will be used later in the program.
- After clicking the Submit button, an OTP will be sent to your registered mobile number; you need to enter the OTP and click on the Submit Button, and your account will be created.
Getting the Code for Sending Message Using Java
- In this step, what we need to do is that, we have to copy the code for sending messages using Java through BulkSMS API.
- In order to do that, go to this webpage https://www.bulksms.com/developer/json/v1/, then scroll down a little bit, and at the right sidebar, you will find the code for Java as shown in the figure below.
- Copy the Code.
- After copying the code, we need to make some adjustments in that code so that we will be able to send the OTP to the desired mobile number using the Java Program.
Creating Java Project in Eclipse IDE
I will use Eclipse IDE for this program. you can use any IDE like NetBeans or IntelliJ IDEA, the coding will be the same.
- Go the File>>New>>Java Project.
- Give a name to your project (SendOTP in this example), and click on the Finish Button.
- Now, right-click on the src folder under the SendOTP Project to create a new Java Class as shown in the figure below.
- Now, give a name to your class (MainClass in this example). I have given the class name as MainClass because the code we have copied from the BulkSMS also has their class name as MainClass.
- Next, Click on the finish button.
Final Code
- Now, we will paste the code that we have copied from the BulkSMS, add some codes, and make some adjustments so that we will be able to send the OTP to the desired mobile number.
- The explanations of the code are given in the comments.
- The Final code is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import java.net.*; import java.util.Base64; import java.io.*; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; public class MainClass { public static void main(String[] args) { // This URL is used for sending messages String myURI = "https://api.bulksms.com/v1/messages"; // change these values to match your own account String myUsername = "mehtabhameed"; //Your Username that you have created while account registration String myPassword = "1234"; //Your Password that you have created while account registration //Code for generating OTP using Random class Random random= new Random(); int min=100000; int max=9999999; int otp=random.nextInt((max-min)+min); /* the details of the message we want to send * put the desired mobile number in which you want to send the OTP */ String myData = "{to: \"+915454545454\", body: \"OTP is : "+otp+"\"}"; URL url; try { url = new URL(myURI); HttpURLConnection request=(HttpURLConnection) url.openConnection(); request.setDoOutput(true); // supply the credentials String authStr = myUsername + ":" + myPassword; String authEncoded = Base64.getEncoder().encodeToString(authStr.getBytes()); request.setRequestProperty("Authorization", "Basic " + authEncoded); // we want to use HTTP POST request.setRequestMethod("POST"); request.setRequestProperty( "Content-Type", "application/json"); try ( // write the data to the request OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream())) { out.write(myData); } // try ... catch to handle errors nicely try { // make the call to the API InputStream response = request.getInputStream(); try (BufferedReader in = new BufferedReader(new InputStreamReader(response))) { String replyText; while ((replyText = in.readLine()) != null) { System.out.println(replyText); } } } catch (IOException ex) { System.out.println("An error occurred:" + ex.getMessage()); // print the detail that comes with the error try (BufferedReader in = new BufferedReader(new InputStreamReader(request.getErrorStream()))) { // print the detail that comes with the error String replyText; while ((replyText = in.readLine()) != null) { System.out.println(replyText); } } } request.disconnect(); } catch (MalformedURLException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } } } |
Adjustments Done in the Code
- Changed the Values to Match our own Username and Password that we have created during the registration process.
1 2 |
String myUsername = "mehtabhameed"; //Your Username that you have created while account registration String myPassword = "1234"; //Your Password that you have created while account registration |
- Added code for generating random number for the purpose of OTP using Random class of Java.
1 2 3 4 |
Random random= new Random(); int min=100000; int max=9999999; int otp=random.nextInt((max-min)+min); |
- Put the desired mobile number in which we want to send the OTP along with the message of OTP.
1 |
String myData = "{to: \"+915454545454\", body: \"OTP is : "+otp+"\"}"; |
How to Generate OTP and Send to Mobile in Java Source Code
- You can download the source code of the project by clicking on the button below.
So this was all from this tutorial about How to Generate OTP and Send to Mobile in Java. If you have any questions regarding this post, then let me know by commenting below.
People Are Also Reading….
- How to Create Calculator in Java Swing
- 11 Best Site to Learn Java Online
- Menu Driven Program in Java Using Switch Case
- How to Create Tic Tac Toe Game in Java
- How to Create Login Form in Java Swing
- Registration Form In Java with Database Connectivity
- How to Create Splash Screen In Java
- How to Create Mp3 Player in Java
- Object-Oriented Programming in Java Questions and Answers