Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Send SMS Messages in Java Using HTTP Requests

DZone's Guide to

How to Send SMS Messages in Java Using HTTP Requests

In this article I am going to present a solution about sending SMS messages in Java for those developers and marketers who think – like me – that SMS is not dead.

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

Hello Everyone,

In this article I am going to present a solution about sending SMS messages in Java for those developers and marketers who think – like me – that SMS is not dead. Using this Java SMS example, you will be able to send a huge amount of SMS text messages from your own Java application with the help of an SMS Gateway. This way, you will be able to integrate a bulk SMS solution into your IT system easily.


Download Source Code for Java SMS Example:

http://mobile.dzone.com/sites/all/files/Source-Code-Java-SMS-Example-HTTP_0.zip


Introduction to the significance of SMS messaging

Before starting the coding, let’s take a look at the present of SMS messaging. Although, nowadays SMS messaging is not the most popular way of mobile communication, but it is still alive. Nay! It is an expressly widely used marketing tool in many countries all over the World such as in the USA, UK, French, Brazil, Spain, Russia, Germany, etc.

Although the significance of mobile web and mobile instant messaging (MIM) has grown, according to the experts, web campaigns alone are going to get left behind. In their opinion, unified business communication has never been more important than now.  Marketers say that unified approach across all channels is necessary. If a company want to reach their target audience in today’s IT society, marketers will need to develop unified internet marketing strategies. For builing a strong and marketable brand, this strategy should combine responsive web design, mobile apps, SMS marketing, etc., with direct marketing, email marketing, etc.


If you still think that SMS messaging is dead, please let me present some interesting facts in this topic. 


Did you know?

1.  Some 5.1 billion out of the 6.8 billion people on Earth own a mobile phone - that's a huge market. 

2.  There are twice as many active SMS users in the world than active users of email.

3.  On average, it takes 90 minutes for someone to respond to an SMS (by comparison, the response time in case of e-mail is 90 minutes).

4.  Around 98 per cent of all SMS messages are opened, but only 20 per cent of emails are looked at.


Figure 1: Facts about SMS messaging


Summarizing, despite the decline of SMS usage among comsumers, businesses still continue to use it for more important, time-sensitive messaging because of its high open-rate. 


Introduction to my Java SMS solution

For this reason I have decided to dig deeper in programming bulk SMS solutions. I prefer using HTTP requests and responses if it possible, because this is a simple way to send data from an application to an other one. Since Java has native method calls to send HTTP requests, HTTP provides a great way to send SMS messages to remote mobile phones.

The following figure illustrates how my application works. The three main participants of the solution are the followings: your Java SMS application; an SMS Gateway and the mobile phone user.


Figure 2: How to send SMS messages in Java through HTTP

  • Your Java SMS application: This is a software written in Java that can be used to send SMS messages. A basic SMS application will be described in this article, but it can be freely extended according to your specific needs. I used HTTP to establish connection between the Java application and the SMS Gateway.
  • SMS Gateway: An SMS Gateway allows your PC to send or receive SMS messages to or from a telecommunications network. It is able to send the SMS messages coming from your Java application through HTTP to the SMSC (Short Message Service Center) of the Mobile Service Provider via SMPP IP SMS connection or a GSM modem. (The SMSC is a network element in the mobile telephone network that stores, forwards, converts and delivers SMS messages.) To be able to send SMS messages using HTTP, you will need an SMS Gateway that has a built-in webserver. (It allows you to send SMS text messages from your application by calling an URL (HTTP Get) or using the HTTP Post method.) For this reason I searched an SMS gateway supporting HTTP that is compatible with my Windows PC. As you can se below, I ignored the Paid Search (Adwords) and I selected the first organic search result to test my application. (It was Ozeki NG SMS Gateway that provides an HTTP SMS API.)



    Figure 3: Search results for „http sms gateway windows”


  • Mobie phone user: This is the endpoint in case of sending SMS messages. This is the recipient of the SMS you wish to send that can be your customer, your business partner, a colleague, a friend or any other. The SMS that has been sent from your Java application will be sent the telephone number of this user.


Code explanation for my Java SMS application

If you read this aticle, you are probably a Java developer. Before getting started the development, I recommend you to make sure that all the necessary prerequisites is installed on your PC:




Step 1: Create a new Java project

Well, are you ready? If so, let’s create a new Java Project in Eclipse:

File > New > Java Project

Define a Projectname for your project in the pop-up window (for example Java-SMS-Application-HTTP), then click on the Finish button:


Figure 4: Create new Java Project in Eclipse


Step 2: Define a new class

After this, you need to define a new Java class:

File > New > Class

In the pop-up window specify the Source folder by clicking on the Browse button next to this line. Open the dropdown menu of the new Java project that you have created previously (above), then select its src folder. This way, the OK button will be active, so click on it:


Figure 5: Source folder selection in Eclipse


Having done the source folder selection, you need to specify a Name for the new class. Please note that the use of the default package is discouraged, so please enter a unique name (for example Java_sms_httprequest). If you click on the Finish button, the creation of the new class will be completed:


Figure 6: Create new Java class in Eclipse


Now you need to import the java.net.* package to be able to implement the SMS application. At this point your code should look like this:

import java.net.*;

public class Java_sms_httprequest {

}

Now take a look at the main method. Here you need to specify the telephone number of the recipient(s), the text of the SMS message and the sender’s phone number. As it can be seen below, you also need to provide the username* and the password* of the SMS gateway that is used for SMS messaging. To be able to connect to the SMS gateway through HTTP, you need to provide the URL* of the SMS gateway (requestUrl).

public static void main(String[] args) {
try {
String recipient = "+441234567890";
String message = " Greetings from Mr. Gupta! Have a nice day!";
String username = "admin";
String password = "abc123";
String originator = "+440987654321";

String requestUrl  = "http://127.0.0.1:9501/api?action=sendmessage&" +
 "username=" + URLEncoder.encode(username, "UTF-8") +
 "&password=" + URLEncoder.encode(password, "UTF-8") +
 "&recipient=" + URLEncoder.encode(recipient, "UTF-8") +
 "&messagetype=SMS:TEXT" +
 "&messagedata=" + URLEncoder.encode(message, "UTF-8") +
 "&originator=" + URLEncoder.encode(originator, "UTF-8") +
 "&serviceprovider=GSMModem1" +
 "&responseformat=html";



URL url = new URL(requestUrl);
HttpURLConnection uc = (HttpURLConnection)url.openConnection();

System.out.println(uc.getResponseMessage());

uc.disconnect();

} catch(Exception ex) {
System.out.println(ex.getMessage());

}

}


* How to find out the required username, password and requestURL?

In case of Ozeki NG, the default username is „admin” and the password is abc123 by default.

Now let’s see the requestUrl. If you want to send SMS messages, the following URL format should be used:

http://127.0.0.1:9501/api?action=sendmessage&username=UUUUU&password=PPPPP&
recipient=NNNNN&messagetype=MMMMM&messagedata=DDDDD


  • 127.0.0.1 should be substituted the IP address or host name of the PC your SMS gateway is installed on. The 9501 is the default port of this gateway.
  • After this you need to add the action parameter to the request (it specifies the HTTP API command). It has only one value: sendmessage.
  • "UUUUU" and "PPPPP" should be replaced to the username and password that was described below.
  • „NNNNN” should be replaced to the phone number that you wish to send the SMS message to.
  • To send text SMS messages you need to use the "SMS:TEXT" message type. 
  • The message data refers to the text of the SMS message. It should be written with UTF-8 characters. 
  • Other parameters can also be added to the request. For example the originator. It should be replaced to the telephone number of the sender party.



Test the application

If you have any SMS Gateway with service provider connection (and you have contracted with a mobile service provider, such as T-Mobile, AT&T, Vodafone, etc.), just run the application and wait for the incoming SMS. The SMS will be transmitted through the configured mobile service provider connection. In my opinion you can follow the whole process in any SMS gateway if that creates log files.

But what if you have not got any installed service provider connection? No problem. You can test the application by simulating the SMS sending. Below I will present how to test your application freely using Ozeki NG:

  • After opening the SMS gateway, click on the „Add service provider” link on the left side of the screen.
  • Then search the „HTTP Server Connection” on the right panel and click on the Install button next to it. (The HTTP Server protocol makes it possible for service providers to use HTTP requests to pass incoming messages to your service. This connection option can be used as a "Virtual phone" for software development purposes.)
  • On the next window click on the OK button:


    Figure 7: Install HTTP Server Connection in the SMS Gateway

  • Go back into the Eclipse Java IDE and now you can run the application.
  • You can check the results if you go back to the SMS gateway. Click on the Events menu item of the previously created HTTP Server. The log shows if your SMS has been sent successfully:


    Figure 8: The log of the HTTP Server Connection in the SMS Gateway

INFO 3322 in the log refers to that the SMS gateway received the SMS from your application. INFO 3327 shows that the SMS was sent to the recipient’s mobile device successfully. If these 2 lines appeared in the log, it means that your application works well, that is your software is able to send SMS messages. 


Congratulations!

01/14/2015 14:58:27 - INFO 3322: Sending message (try 1/1) admin;SMS:TEXT;fb92ebd6-33b5-4399-a622-3195498e40ec;admin;+441234567890; Greetings from Mr. Gupta! Have a nice day!;  using service provider connection 'HTTPServer0(HTTPServer3)'
01/14/2015 14:58:27 - INFO 3327: Message successfully sent. Reference: fb92ebd6-33b5-4399-a622-3195498e40ec


Please note that this HTTP Server Connection is recommended just for test purposes. It was just the simulation of SMS sending. It can be perfectly used to test your development, but if you want to send SMS messages actually, you need to install a GSM modem connection or an IP SMS connection.


References and other useful links

[1]  https://www.blueinteractiveagency.com/seo-blog/2014/12/10-digital-marketing-trends-2015/

[2]  http://digitalmarketingmagazine.co.uk/mobile-digital-marketing/7-key-statistics-for-sms-marketing/558

[3]  http://blog.textanywhere.net/post/2014/04/10/15-Interesting-Facts-about-SMS-.aspx

[4]  http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests

[5]  http://en.wikipedia.org/wiki/SMS_gateway

[6]  http://en.wikipedia.org/wiki/Short_message_service_center

[7]  http://www.eclipse.org/downloads/

[8]  http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html


[9]  http://ozekisms.com/index.php?owpn=112

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
java ,mobile ,jdk ,sms ,http requests ,java sms

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}