How to send SMS from Java
The following example console application written in Java programming language is going to show you the way you can send HTTP requests to the SMS Gateway and get the response message as well. These HTTP requests can be used for sending SMS messages and you can easily configure the details of the SMS message by modifying the variables which contain all information regarding the SMS message.
What is a Java SMS API?
The Java SMS API enables you to implement SMS services into your Java Application. The API communicates with the SMS Gateway using HTTP requests which sends the message and returns with a response message.
Prerequisites
Send SMS from Java
- Open Apache NetBeans IDE
- Click on 'New project...'
- Create a new Java Application
- Name the project and the package
- Create a new Java Class
- Copy-Paste the example source code below
- Run the Java Application
- Select the main class if needed
Java SMS source code example
The following example source code written in Java programming language is free to use, you can simply implement it into your project, or you can modify the source code to use it for other projects or applications. If you would like to run this example code, you just need to create a new Java application with a single Java class and run the project as you can see it in the step instructions and the video above.
package tester; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpApiTester { public static void main(String[] args) { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (GeneralSecurityException e) { System.out.println(e.getMessage()); } try { StringBuilder sendString = new StringBuilder(); String username = "john"; String password = "Xc3ffs"; String messagetype = "SMS:TEXT"; String httpUrl = "https://127.0.0.1:9508/"; String recipient = URLEncoder.encode("+36201324567", "UTF-8"); String messagedata = URLEncoder.encode("TestMessage", "UTF-8"); sendString.append(httpUrl).append("api?action=sendmessage"). append("&username=").append(username).append("&password="). append(password).append("&recipient=").append(recipient). append("&messagetype=").append(messagetype).append("&messagedata="). append(messagedata); System.out.println("Sending request: " + sendString.toString()); URL url = new URL(sendString.toString()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader br = null; System.out.println("Http response received: "); if (con.getResponseCode() == 200) { br = new BufferedReader(new InputStreamReader(con.getInputStream())); String strCurrentLine; while ((strCurrentLine = br.readLine()) != null) { System.out.println(strCurrentLine); } } else { br = new BufferedReader(new InputStreamReader(con.getErrorStream())); String strCurrentLine; while ((strCurrentLine = br.readLine()) != null) { System.out.println(strCurrentLine); } } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
Step 1 - Open Apache NetBeans IDE
The first step is to create a Java application that can send SMS messages is to open Apache NetBeans IDE on your computer. Apache NetBeans provides editors, wizards, and templates to help you create applications in Java, PHP and many other languages. If you haven't downloaded Apache NetBeans yet, you can download it from the Prerequisites section. After you installed it, you just have to open it from your desktop like in Figure 1.
Step 2 - Create a new Java project
After you opened Apache NetBeans IDE, it opens up with the main window. Here, you can create the Java Application that needed to send SMS messages. For that, as you can see it in Figure 2, click on 'File' on the toolbar, and here, select the 'New project...' option.
Step 3 - Select Java Application
Next, a new window pops up, that contains all types of projects that can be created in Apache NetBeans. Here, you can create the simple Java Application, or you can select from more advanced types of projects. For this example you can use the simple Java Application, so select it from the list, and like in Figure 3 click Next.
Step 4 - Configure the Java Application
In the next step, you need to do some basic configuration for the Java Application. As you can see it in Figure 4, you can give a name for the project. You can also set the location of the project and lastly you can specify a name for the package as well. If you finished with the configuration, just click on Finish.
Step 5 - Create a new Java Class
The create Java Application project is empty, so it does not contain any file with source code, so you need to create one. For that, select the package of your project, and click with the right button on your mouse. From the pop-up window, as Figure 5 shows that, select New, and after that, click on 'Java class...' to create a new Java class in your application.
Step 6 - Configure the Java class
Before finishing the creation of the Java class, you need to specify a name for the class. That can be easily done as Figure 6 shows that. After you gave the right name for the Java class, just click on the Finish button to successfully create the Java class.
Step 7 - Paste the source code
The next thing, that you need to do is to place the example code into your Java Application. For that, just scroll up to the example code copy the whole source code to your clipboard and place it into your newly created Java class. At this point, you can run the Java Application, so just click on the Run button on the toolbar. In the first run, as Figure 7 demonstrates that, you need to select the Main class for execution. So, just select the HttpApiTester class, and click on 'Select Main class'.
Step 8 - See the result of the application
If you have done everything right till this point, the application starts, and you will be able to see the result in the console window as Figure 8 shows that. This window prints the HTTP request that was initiated and sent to the SMS Gateway, and it also prints the response from the SMS Gateway which indicates that the delivery of the SMS message was successful or not.
Step 9 - Check the send result in the Ozeki log
In Ozeki 10 SMS Gateway, you can follow what messages sent by your application, since the HTTP API service logs every event that occurred during the time it is enabled. So, after you opened the SMS Gateway, and selected the details of the HTTP API service, you will be able to see the events. As Figure 9 shows that, the service logged an event, when the example Java Application sent the HTTP request to the service.
The way that SMS Gateway processes the messages can be also viewed back by the events. For that, open the HTTP API User connection, that you had to configure before. Figure 10 demonstrates that how the connection handles the HTTP request and send the message to the recipient that you specified in your Java Application.
Summary
You have learned how to send SMS from Java from this article. This means that you can implement SMS services into your Java applications. The foundation of this solution is the Ozeki SMS Gateway. It means that you will have no performance issues or any latency in SMS sending. This way your Java solutions can satisfy more customer needs and it will be versatile. It also will be able to make information flow way faster and easier.
To have a better understanding of the whole system, feel free to check the Ozeki tutorial pages about receiving SMS in Java, or try implementing SMS services in other projects. For example, use the HTTP SMS API with PHP.
The next thing to do is to download the Ozeki SMS Gateway and start developing now!
More information