Examples

Example code is located here covering a variety of languages with and without . We hope that you find the code clear, simple and accurate. 

 

HTTP (simple) API

The code samples show the sending of a message to a single mobile number using the destaddr field by a comma (e.g. “447968000111,447720000111,3378100100”).

Java

The following sample application written in Java sends an SMS text message to a single mobile telephone. The code uses HTTPS to communicate with HSL’s SMS gateway.

javaSuperSimpleHTTPExample.java

import java.net.*;
import java.io.*;
import java.security.*;

public class SuperSimpleHTTPExample {
	public static void main(String[] args) {
		try {
			// These variables fill out the various parts described in the 
			// API specification
			String host = "sms.haysystems.com";
			String port = "443";
			String action = "sendtxt";
			String client_id = "";
			String text = "this is a test message";
			String destaddr = "";
			String password = "";
			// Build and encode the URL.
			// Note we are careful to URL-encode the message content as it is
			// the only part of the URL likely to contain reserved characters.
			String url = "https://" + host + ":" + port + "/" + action;
			url += "/?client_id=" + client_id + "&text=";
			url += URLEncoder.encode(text, "UTF-8") + "&destaddr="+ destaddr;
			url += "&password=" + password;
			// Make a URL object, ready for the call
			URL urlObject = new URL(url);
			// Actually make a connection
			HttpURLConnection connection =
			(HttpURLConnection)urlObject.openConnection();
			connection.setDoInput(true);
			connection.connect();
			// Check the response
			int responseCode = connection.getResponseCode();
			if(responseCode == 200) {
				// Read the server's response
				BufferedReader in = new BufferedReader(
													   new InputStreamReader(connection.getInputStream()));
				System.out.println("Submission result: " + in.readLine());
				in.close();
			} else {
				// There was an error
				System.err.println("Server responded with code " + responseCode);
			}
		} catch(Exception e) {
			System.err.println("Unable to make HTTP request due to an exception:");
			e.printStackTrace();
		}
	}
}

The following sample application written in Java sends a UCS2 or Unicode message to a single mobile telephone. The application uses HTTPS to communicate with HSL’s SMS gateway.

javaSuperSimpleUCS2HTTPExample.java

import java.net.*;
import java.io.*;
import java.security.*;

public class SuperSimpleUCS2HTTPExample {
	public static void main(String[] args) {
		try {
			// These variables fill out the various parts described in the
			// API specification
			String host = "sms.haysystems.com";
			String port = "443";
			String action = "senducs";
			String client_id = "";
			String destaddr = "";
			String ucs2 = "06450631062d0628064b06270020063906270644064500200021";
			String password = "";
			
			// Build and encode the URL.
			// Note we are careful to URL-encode the message content as it is
			// the only part of the URL likely to contain reserved characters.
			String url = "https://" + host + ":" + port + "/" + action;
			url += "/?client_id=" + client_id + "&destaddr="+ destaddr;
			url += "&message=" + ucs2 + "&password=" + password;
			
			// Make a URL object, ready for the call
			URL urlObject = new URL(url);
			
			// Actually make a connection
			HttpURLConnection connection =
			(HttpURLConnection)urlObject.openConnection();
			connection.setDoInput(true);
			connection.connect();
			
			// Check the response
			int responseCode = connection.getResponseCode();
			if(responseCode == 200) {
				// Read the server's response
				BufferedReader in = new BufferedReader(
													   new InputStreamReader(connection.getInputStream()));
				System.out.println("Submission result: " + in.readLine());
				in.close();
			} else {
				// There was an error
				System.err.println("Server responded with code " + responseCode);
			}
		} catch(Exception e) {
			System.err.println("Unable to make HTTP request due to an exception:");
			e.printStackTrace();
		}
	}
}

The following sample application written in Java queries a database for messages that are encoded in the database in UTF-8 and then sends a UCS2 / Unicode message to each mobile telephone. The messages to be sent as SMS using UCS2 are in Greek, Spanish, English, Arabic, Japanese, Tibetan and Chinese. The application uses HTTPS to communicate with HSL’s SMS gateway.

javaHSLSMSDatabaseExample.java

/*
 * HSLSMSDatabaseExample.java
 *
 * Copyright (c) 2014 Hay Systems Ltd. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted
 * provided that this copyright notice appears in all copies.
 *
 * HSL MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. HSL SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

import java.sql.*;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.*;
import java.io.*;
import java.security.*;

/*
 
 Run the following from the command line to create and populate the PostgreSQL database:
 
 psql -U postgresl -f hslsmsdb-init.sql
 
 Compile and run Java app:
 
 javac HSLSMSDatabaseExample.java
 java -Dfile.encoding=UTF-8 HSLSMSDatabaseExample
 
 */

public class HSLSMSDatabaseExample {
	
	static String app;
	
	public static void senducs(String destaddr, String ucs2message) {
		
		try {
			// These variables fill out the various parts described in the
			// HTTP (simple) API specification at http://developers.hslmobile.com
			String host = "sms.haysystems.com";
			String port = "443";
			
			// These variables are from your account configuration document.
			String client_id = ""; // clientid
			String password = ""; // password
			
			// Build and encode the HTTPS URL
			String url = "https://" + host + ":" + port + "/senducs";
			url += "/?client_id=" + client_id + "&destaddr="+ destaddr;
			url += "&message=" + ucs2message + "&password=" + password;
			
			// Make a URL object, ready for the call
			URL urlObject = new URL(url);
			
			// Actually make a connection
			HttpURLConnection connection =
			(HttpURLConnection)urlObject.openConnection();
			connection.setDoInput(true);
			connection.connect();
			
			// Check the response
			int responseCode = connection.getResponseCode();
			if(responseCode == 200) {
				// Read the server's response
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				System.out.println("Submission result: " + in.readLine());
				in.close();
			} else {
				// There was an error
				System.err.println("Server responded with code " + responseCode);
			}
		} catch(Exception e) {
			System.err.println("Unable to make HTTP request due to an exception:");
			e.printStackTrace();
		}
	}
	
	private static String stringToUCS2Hex( String in )
	{
		String out = "";
		byte[] array = {};
		try {
			array = in.getBytes("UTF-16BE"); // UTF16 = UCS2; use big endian (codepage first byte)
		} catch (UnsupportedEncodingException ex) {
			Logger lgr = Logger.getLogger(app);
			lgr.log(Level.WARNING, ex.getMessage(), ex);
		}
		for(int i=0;i<array.length;i++) {
			out = out + String.format("%02x",array[i]);
		}
		return out;
	}
	
	public static void main(String[] args) {
		app = "HSLSMSDatabaseExample";
		Connection con = null;
		Statement st = null;
		ResultSet rs = null;
		String url = "jdbc:postgresql://localhost/hslsms?characterEncoding=utf8";
		String user = "app001";
		String pass = "a9s@987f";
		try {
			con = DriverManager.getConnection(url, user, pass);
			st = con.createStatement();
			rs = st.executeQuery("SELECT message,mobileno FROM sms"); // query database for message text and mobile number
			while (rs.next()) { String message = rs.getString(1);
				String mobileno = rs.getString(2);
				String ucs2message = stringToUCS2Hex(message); // convert message to hex formatted UCS2
				System.out.println(message);
				System.out.println(mobileno);
				System.out.println(ucs2message);
				senducs( mobileno, ucs2message ); // submit UCS2 message to HSL for delivery to mobile
			}
		}
		catch (SQLException ex) {
			Logger lgr = Logger.getLogger(app);
			lgr.log(Level.SEVERE, ex.getMessage(), ex);
		}
		finally {
			try {
				if (rs != null) { rs.close(); }
				if (st != null) { st.close(); }
				if (con != null) { con.close(); }
			}
			catch (SQLException ex) {
				Logger lgr = Logger.getLogger(app);
				lgr.log(Level.WARNING, ex.getMessage(), ex);
			}
		}
	}
}

Supporting SQL file for creating and populating a PostgreSQL database:

javahslsmsdb-init.sql

CREATE USER app001 WITH PASSWORD 'a9s@987f';
CREATE DATABASE hslsms WITH OWNER app001 ENCODING 'UTF8';
-- connect to database
\c hslsms
CREATE TABLE sms ( message text, mobileno text, id serial );
GRANT ALL ON TABLE sms TO app001;
-- add example messages (UTF-8 message texts)
INSERT INTO sms (message,mobileno) VALUES ('Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα.','447892000000'); -- Greek
INSERT INTO sms (message,mobileno) VALUES ('Puedo comer vidrio, no me hace daño.','447892000001'); -- Spanish
INSERT INTO sms (message,mobileno) VALUES ('I can eat glass and it does not hurt me.','447892000002'); -- English
INSERT INTO sms (message,mobileno) VALUES ('أنا قادر على أكل الزجاج و هذا لا يؤلمني.','447892000003'); -- Arabic
INSERT INTO sms (message,mobileno) VALUES ('私はガラスを食べられます。それは私を傷つけません。','447892000004'); -- Japanese
INSERT INTO sms (message,mobileno) VALUES ('ཤེལ་སྒོ་ཟ་ནས་ང་ན་གི་མ་རེད།','447892000005'); -- Tibetan
INSERT INTO sms (message,mobileno) VALUES ('我能吞下玻璃而不伤身体。','447892000006'); -- Chinese

C++ / Linux

The following sample application written in C++ on Linux sends an SMS message to a single mobile telephone. The application uses HTTP to communicate with HSL’s systems. cpp

-*-

C#

The following sample application written in C# sends an SMS text message to a single mobile telephone. The application uses HTTPS to communicate with HSL’s systems.

csharp

--*--

C++ / Windows (BSD sockets)

The following sample application written in C++ sends an SMS text message to a single mobile telephone. The application uses HTTP to communicate with HSL’s systems.

cpp

--*--

PHP

The PHP code snippet sends an SMS text message to a single mobile telephone. The code uses HTTPS to communicate with HSL’s SMS gateway. Configuration information for your account can be found in the configuration document sent to you when your account was set-up.

php

<?php

// These variables fill out the various parts described in the API
// specification
$host = 'sms.haysystems.com';
$action = 'sendtxt';
$clientid = '<your client ID>';
$text = 'this is a test message';
$destaddr = '<some fully-qualified MSISDN>';
$secret = '<your secret>';

// Compute the MD5 hash (digest)
$hash = md5($secret . $text . $destaddr);

// Build and encode the URL.
// Note we are careful to URL-encode the message content as it is the only part
// of the URL likely to contain reserved characters.
$url = "https://$host/$action/?clientid=$client_id&text=" . urlencode($text) . "&destaddr=$destaddr&key=$hash";

// Make the HTTP call (you could use CURL on PHP 4+) we get the content that
// readfile would normally output directly with the ob_start, ob_get_contents
// and ob_end_clean calls.
ob_start();
$result = @readfile($url);
$data = ob_get_contents();
ob_end_clean();

// Examine the results
if ($result === false) echo "Could not make HTTP request; is the URL correct? ($url)";
else echo "Submission result: $data";

?>

Web Service (SOAP/XML)

The code sample shows the sending of a message to a single mobile number using the destaddr field by a comma (e.g. “447968000111,447720000111,3378100100”).

C#/.NET

The following is an extract of the minimum necessary user code in C#/.NET to send a message where SMS has been used as the web reference.

csharp

SMS.ShortMessageService sms = new SMS.ShortMessageService(); 
SMS.Outcome[] result = sms.sendText( "acc80964", "5611e621", "447123456789", "Hello World", null ); 
if ( ( result.Length > 0 ) && ( result[ 0 ].success ) )
    outcome.Text = "Success";
else
    outcome.Text = "Fail";