ES

Send SMS with Java - Examples and Complete Guide

Java code examples for integration with the LabsMobile SMS API

The following are the examples of programming code in Java language to send SMS messages through the LabsMobile platform API.

This documentation is designed for you to connect your applications with the LabsMobile platform and automate the sending of SMS messages. The main objective of the integration of these applications is the sending of SMS messages and related communications.

Advice We recommend using our API SMS http/POST in JSON format for any integration with the LabsMobile platform. But we have other API versions that you can use depending on your environment and requirements.

With these examples you will be able to perform the integration of the following functionalities:

  • Send SMS messages individually or in bulk.
  • Check your account balance.
  • Receive delivery confirmation and/or error notifications corresponding to the messages sent.
  • Obtain notification and data of the messages received in the virtual numbers contracted.

The LabsMobile API SMS uses a common base URL for all requests: https://api.labsmobile.com.

It is highly recommended to use a URL that includes the HTTPS protocol in any version of the API.

Authentication is done with the username and an API token, myUsername:myToken. You must create the API token from the API Settings section of your account.


Send SMS with http/POST

Here is an example of Java language code to send SMS messages using the API SMS http/POST that uses the JSON format for the information exchange variables.

As you can see, you need to create a structure in JSON format containing all the necessary parameters for sending and make a HTTP/POST call with this data in the body of the request.

Simple sending to a single recipient with http/POST (Java)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class App {
 public static void main(String[] args) throws UnirestException {
   Unirest.setTimeouts(0, 0);
   HttpResponse<String> response = Unirest.post("https://api.labsmobile.com/json/send")
       .header("Content-Type", "application/json")
       .basicAuth("myUsername", "myToken")
       .header("Cache-Control", "no-cache")
       .body(
         "{\"message\":\"Your verification code is 123\", \"tpoa\":\"Sender\",\"recipient\":[{\"msisdn\":\"12015550123\"}]}")
       .asString();
   System.out.println("Status code: " + response.getBody());
 }
}
              

Bulk sending to multiple recipients with http/POST (Java)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class App {
 public static void main(String[] args) throws UnirestException {
   Unirest.setTimeouts(0, 0);
   HttpResponse<String> response = Unirest.post("https://api.labsmobile.com/json/send")
       .header("Content-Type", "application/json")
       .basicAuth("myUsername", "myToken")
       .header("Cache-Control", "no-cache")
       .body(
         "{\"message\":\"Don't miss our Sale! Use code XXXX123 for 20% off.\", \"tpoa\":\"Sender\",\"recipient\":[{\"msisdn\":\"12015550123\"},{\"msisdn\":\"12015550124\"},{\"msisdn\":\"12015550125\"}]}")
       .asString();
   System.out.println("Status code: " + response.getBody());
 }
}
                

Positive result
{
  "subid": "65f33a88ceb3d",
  "code": "0",
  "message": "Message has been successfully sent."
}
  

Wrong result
{
  "subid": "65f7f7041385d",
  "code": "35",
  "message": "The account has no enough credit for this sending"
}
  

All error codes can be found in API documentation, error codes.

For more details on the available parameters and configuration options, see the official documentation at:


Send SMS with http/GET

This is an example of code in Java language to send SMS messages using the SMS API http/GET.

As you can see, you must pass a series of GET variables in the same URL and make a HTTP call. It is important to encode all values as URL using the URLEncoder.encode() function.

Important The SMS http/GET API transmits credentials (username and API token) unencrypted and unsecured. We recommend using this API GET only when absolutely essential and use the API SMS http/POST instead.

Simple single-recipient sending with http/GET (Java)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
   public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {
       String username = "myUsername";
       String token = "myToken";
       String message = "Your verification code is 123";
       String[] msisdn = {"12015550123"};

       String url = "https://api.labsmobile.com/get/send.php?username=" +
               URLEncoder.encode(username, "UTF-8") +
               "&password=" + URLEncoder.encode(token, "UTF-8") +
               "&message=" + URLEncoder.encode(message, "UTF-8") +
               "&msisdn=" + URLEncoder.encode(String.join(",", msisdn), "UTF-8");

       Unirest.setTimeouts(0, 0);
       HttpResponse<String> response = Unirest.get(url).asString();
       System.out.println("Status code: " + response.getBody());
   }
}
                

Bulk sending to multiple recipients with http/GET (Java)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
   public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {
       String username = "myUsername";
       String token = "myToken";
       String message = "Don't miss our Sale! Use code XXXX123 for 20% off.";
       String[] msisdn = {"12015550123,12015550124,12015550125"};

       String url = "https://api.labsmobile.com/get/send.php?username=" +
               URLEncoder.encode(username, "UTF-8") +
               "&password=" + URLEncoder.encode(token, "UTF-8") +
               "&message=" + URLEncoder.encode(message, "UTF-8") +
               "&msisdn=" + URLEncoder.encode(String.join(",", msisdn), "UTF-8");

       Unirest.setTimeouts(0, 0);
       HttpResponse<String> response = Unirest.get(url).asString();
       System.out.println("Status code: " + response.getBody());
   }
}
                

Positive result
{
  "subid": "65f33a88ceb3d",
  "code": "0",
  "message": "Message has been successfully sent."
}
  

Wrong result
{
  "subid": "65f7f7041385d",
  "code": "35",
  "message": "The account has no enough credit for this sending"
}
  

All error codes can be found in API documentation, error codes.

For more details on the available parameters and configuration options, see the official documentation at:


Account balance inquiry

With this Java code example, you can consult your account balance using the LabsMobile API SMS.

Through a call to this endpoint, you can get information about the amount of credits available in your LabsMobile account. The connection is established through a HTTP/GET request with authentication in the HTTP connection header.

Account balance inquiry (Java)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class App {
 public static void main(String[] args) throws UnirestException {
   Unirest.setTimeouts(0, 0);
   HttpResponse<String> response = Unirest.get("https://api.labsmobile.com/json/balance")
       .header("Content-Type", "application/json")
       .basicAuth("myUsername", "myToken")
       .header("Cache-Control", "no-cache")
       .body("")
       .asString();
   System.out.println("Status code: " + response.getBody());
 }
}
                

Result
{"code":0,"credits":"10"}

  

See the complete documentation at:


Receive status of sent messages

This example script receives a call from the LabsMobile platform when a sent SMS message changes status. To implement this solution, it is essential to configure the appropriate parameters, the confirmation URL in the ackurl parameter in the request or the default URL in the API Settings of your account.

Therefore, it is necessary to publish a script like this in your system so that our platform calls the URL when a status change occurs in any of the sent messages.

The example code obtains the URL parameters using the global $_GET variable and then assigns these parameters to local variables.

Script for receiving sent message status (Java)
import static spark.Spark.*;

public class App {
   public static void main(String[] args) {
       port(3000);

       get("/", (req, res) -> {
         String acklevel = req.queryParams("acklevel");
         String credits = req.queryParams("credits");
         String msisdn = req.queryParams("msisdn");
         String status = req.queryParams("status");
         String subid = req.queryParams("subid");
         String timestamp = req.queryParams("timestamp");

         System.out.println("Variable acklevel: " + acklevel);
         System.out.println("Variable credits: " + credits);
         System.out.println("Variable msisdn: " + msisdn);
         System.out.println("Variable status: " + status);
         System.out.println("Variable subid: " + subid);
         System.out.println("Variable timestamp: " + timestamp);

         return "";
       });
   }
}
                

See the complete documentation at:


Receiving SMS messages

Once you have contracted a virtual number, you will be able to receive messages via API on a specific URL via a HTTP/GET call to a script in your system. Each message received will invoke the URL, transmitting all its data in variables in JSON format.

To activate this functionality you must inform the URL for receiving messages in the Settings of your account.

It is necessary to configure an endpoint in your system so that the LabsMobile platform calls this script when an SMS is received on any of the contracted virtual numbers.

The example code obtains the URL parameters using the global variable $_GET and then assigns these parameters to local variables.

Script for receiving incoming messages (Java)
import static spark.Spark.*;

public class App {
   public static void main(String[] args) {
       port(3000);

       get("/", (req, res) -> {
         String inbound_number = req.queryParams("inbound_number");
         String service_number = req.queryParams("service_number");
         String msisdn = req.queryParams("msisdn");
         String message = req.queryParams("message");
         String timestamp = req.queryParams("timestamp");

         System.out.println("Variable inbound_number: " + inbound_number);
         System.out.println("Variable service_number: " + service_number);
         System.out.println("Variable msisdn: " + msisdn);
         System.out.println("Variable message: " + message);
         System.out.println("Variable timestamp: " + timestamp);

         return "";
       });
   }
}
                

See the complete documentation at:


Start Sending SMS with Java Now

Sending SMS from your Java application is quick and easy. Follow these simple steps to create your account, prepare your environment, and start sending messages to your customers using the LabsMobile API.

Step 1: Create your LabsMobile Account

Sign up for free. Visit the official LabsMobile page: Create account. Confirm your account via the verification email you will receive.

Access your Control Panel. Log in with your username and password. Go to the “API Configuration” section to obtain your API token, necessary to integrate your PHP application.

Step 2: Choose an integration method

Select from:

Check out and adapt the sample code you can find on this page.

Step 3: Send your First SMS

Add credentials. Customize the PHP code with your account's username and API token.

Create and Customize your Message. Define the destination number, the sender, and the content of the message. Optionally activate the simulated mode to avoid consuming credits with your first sends. Check all the sending options and parameters on the documentation page of the chosen integration method.

Send and Verify. Send the message and check the status in the control panel (in the History section) to confirm its correct delivery.


Importance of SMS Sending in Java Applications

Java applications stand out for their ability to offer robust and scalable solutions. Integrating SMS sending is a key component to enhance communication and improve interaction with users. Here we tell you why it is essential:

Direct and Effective Communication

SMS ensures that users receive relevant information in real time, without depending on notifications in applications or emails.

Improved User Experience

Applications that offer instant notifications generate a more personalized and satisfactory experience for end users.

Versatility in Different Sectors

From e-commerce to banking to delivery services, SMS sending can be applied to multiple industries for notifications, alerts, and reminders.

Delivery Reliability

SMS is independent of the Internet connection and compatible with any mobile device. It ensures that messages are delivered even in low connectivity environments and with delivery metrics.


Benefits of Integrating SMS in Java Applications

Integrating SMS into your Java applications provides a competitive advantage that improves both the functionality and performance of your software. Discover the key benefits:

Increase Security with 2FA

SMS allows you to implement two-factor authentication (2FA), strengthening security and reducing fraud.

Automation and Efficiency

Automated SMS handles tasks such as appointment reminders, order confirmations, and status updates, saving time and operational costs.

Greater Customer Loyalty

Fast, personalized communication via SMS improves user relationships and loyalty to your application.

Easy Technical Integration

Java offers ready-made libraries and APIs to integrate SMS sending services with LabsMobile, facilitating fast and hassle-free implementation.

Unlimited Scalability

Bulk SMS sending allows you to scale marketing campaigns, alerts, or notifications, adapting to the growth of your business.

Optimize your Java Application with SMS!
Incorporate SMS sending into your Java application and transform the way you communicate with your users. Contact us for more details about this technological solution.