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.  if you require further examples in Python, Ruby, Java, C#, PHP, Node.js, .NET, C++ or another language.

HTTP (simple) API

The code samples show the sending of a message to a single mobile number using the .  To send to more than one mobile telephone at a time, separate each mobile number in 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 application uses HTTPS to communicate with HSL’s systems.

javaSuperSimpleHTTPExample.java“; 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 systems.

javaSuperSimpleUCS2HTTPExample.java“; 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 systems.

javaHSLSMSDatabaseExample.java“; // 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

Supporting SQL file for creating and populating a PostgreSQL database:

javahslsmsdb-init.sql

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 #include #include #include #include #include #include #include int main(int argc, char* argv[]) { const char* host = “sms.haysystems.com”; const int port = 80; const char* action = “sendtxt”; const char* client_id = ““; const char* text = “this is a test message”; const char* url_encoded_text = “this+is+a+test+message”; const char* destaddr = ““; const char* secret = ““; // Digest variables EVP_MD_CTX md_context; const EVP_MD* md = EVP_md5(); unsigned int md_length; unsigned char md_value[EVP_MAX_MD_SIZE]; // Initialise the digest EVP_DigestInit(&md_context, md); // Feed data into the digest EVP_DigestUpdate(&md_context, secret, strlen(secret)); EVP_DigestUpdate(&md_context, text, strlen(text)); EVP_DigestUpdate(&md_context, destaddr, strlen(destaddr)); // Get the digest and it’s length EVP_DigestFinal(&md_context, md_value, &md_length); // Convert the digest’s raw bytes into a string char lut[] = { ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ }; char* hash = new char[md_length * 2 + 1]; for(int i = 0; i < md_length; i++) { hash[2 * i] = lut[(md_value[i] & 0xF0) >> 4]; hash[2 * i + 1] = lut[md_value[i] & 0x0F]; } hash[md_length * 2] = ‘\0’; // Create the URL int buffer_size = strlen(client_id) + strlen(url_encoded_text) + strlen(destaddr) + strlen(hash) + 64; //52 char* buffer = new char[buffer_size]; sprintf(buffer, “GET /%s/?client_id=%s&text=%s&destaddr=%s&key=%s HTTP/1.0\r\n\r\n”, action, client_id, url_encoded_text, destaddr, hash); // Clean up delete[] hash; // Create the socket int the_socket = socket(AF_INET, SOCK_STREAM, 0); // Set up the address struct sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(port); inet_pton(AF_INET, host, &address.sin_addr); // Connect connect(the_socket, (struct sockaddr *)&address, sizeof(address)); // Variables used for IO int bytes_to_io = strlen(buffer); int total_bytes_iod = 0; int bytes_iod = 0; // Send the request while(total_bytes_iod < bytes_to_io && (bytes_iod = send(the_socket, buffer + total_bytes_iod, bytes_to_io - total_bytes_iod, 0)) != -1) { total_bytes_iod += bytes_iod; } // Read the response buffer_size = 4096; buffer = new char[buffer_size]; bytes_to_io = buffer_size; total_bytes_iod = 0; while(total_bytes_iod < buffer_size && (bytes_iod = recv(the_socket, buffer + total_bytes_iod, buffer_size - total_bytes_iod, 0))) { total_bytes_iod += bytes_iod; } buffer[total_bytes_iod] = '\0'; // Inform the user of the outcome fprintf(stdout, "HTTP response:\n%s\n", buffer); delete[] buffer; return EXIT_SUCCESS; }]]>

PHP

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

php‘; $text = ‘this is a test message’; $destaddr = ‘‘; $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:$port/$action/?client_id=$client_id&text=” . urlencode($text) . “&destaddr=$destaddr&key=$hash”; // Make the HTTP call (you could use CURL on PHP 4+) we nab 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?

‘; echo ”

$url

“; } else { echo ”

Submission result: $data

“; } ?> ]]>

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.

<%@ Import Namespace="System.Security.Cryptography" %> <%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.IO" %> <%@ Page Language="C#" %> Simple C# example of text via the HSL HTTP interface <% // These variables fill out the various parts described in the // interface 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 secret = ““; // Compute the MD5 hash MD5 md5 = new MD5CryptoServiceProvider(); Encoding encoding = Encoding.ASCII; String hashInput = secret + text + destaddr; byte[] hashInputBytes = encoding.GetBytes(hashInput.ToCharArray()); byte[] rawHash = md5.ComputeHash(hashInputBytes); // Convert the raw bytes into a string String hash = “”; for(int i = 0; i < rawHash.GetLength(0); i++) { String coded = Convert.ToString(rawHash[i], 16); if(coded.Length == 1) { coded = "0" + coded; } hash += coded; } // 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 + "/?client_id=" + client_id + "&text=" + Server.UrlEncode(text) + "&destaddr=" + destaddr + "&key=" + hash; // Create an HTTP request WebRequest httpRequest = WebRequest.Create(url); WebResponse httpResponse = httpRequest.GetResponse(); Stream stream = httpResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream); // Make the request and print the result Response.Write("

Submission result: “); Response.Write(reader.ReadToEnd()); Response.Write(“

“); reader.Close(); %> ]]>

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 #include #include #include #include char* compute_md5_hash(const char* input); void init_winsock(void); int main(int argc, char* argv[]) { const char* host = “sms.haysystems.com”; const int port = 80; const char* action = “sendtxt”; const char* client_id = ““; const char* text = “this is a test message”; const char* url_encoded_text = “this+is+a+test+message”; const char* destaddr = ““; const char* secret = ““; // Compute the hash int length = strlen(secret) + strlen(text) + strlen(destaddr) + 1; char* accumulator = new char[length]; sprintf(accumulator, “%s%s%s”, secret, text, destaddr); char* hash = compute_md5_hash( accumulator ); // Create the URL int buffer_size = strlen(client_id) + strlen(url_encoded_text) + strlen(destaddr) + strlen(hash) + 64; //52 char* buffer = new char[buffer_size]; sprintf(buffer, “GET /%s/?client_id=%s&text=%s&destaddr=%s&key=%s HTTP/1.0\r\n\r\n”, action, client_id, url_encoded_text, destaddr, hash); // Clean up delete[] hash; // Initialise winsock init_winsock(); // Create the socket int the_socket = socket(AF_INET, SOCK_STREAM, 0); // Set up the address struct sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(port); unsigned long inet_address = inet_addr(host); memcpy( &(address.sin_addr), &inet_address, 4 ); memset( &(address.sin_zero), ‘\0’, 8 ); // zero the rest of the struct // Connect connect(the_socket, (struct sockaddr *)&address, sizeof(address)); // Variables used for IO int bytes_to_io = strlen(buffer); int total_bytes_iod = 0; int bytes_iod = 0; // Send the request while(total_bytes_iod < bytes_to_io && (bytes_iod = send(the_socket, buffer + total_bytes_iod, bytes_to_io - total_bytes_iod, 0)) != SOCKET_ERROR) { total_bytes_iod += bytes_iod; } // Read the response buffer_size = 4096; buffer = new char[buffer_size]; bytes_to_io = buffer_size; total_bytes_iod = 0; while(total_bytes_iod < buffer_size && (bytes_iod = recv(the_socket, buffer + total_bytes_iod, buffer_size - total_bytes_iod, 0)) > 0) { total_bytes_iod += bytes_iod; } buffer[total_bytes_iod] = ‘\0’; // Inform the user of the outcome fprintf(stdout, “HTTP response:\n%s\n”, buffer); delete[] buffer; closesocket(the_socket); // Clean up winsock WSACleanup(); return EXIT_SUCCESS; } /* * This method computes the MD5 hash of the secret, text and destination * address. It should be clear how this can be extended to other hash * algorithms and arbitrary data. */ char* compute_md5_hash(const char* input) { // Variables used during the hashing process HCRYPTPROV cryptoProvider; HCRYPTHASH rawHash; // Get the cryptographic provider for MD5 hashing // NOTE: This call could (potentially) fail and this should be checked for CryptAcquireContext(&cryptoProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); // Create an object that will perform the hash // NOTE: This call could (potentially) fail and this should be checked for CryptCreateHash(cryptoProvider, CALG_MD5, 0, 0, &rawHash); // Feed data into the hash // NOTE: This call could (potentially) fail and this should be checked for CryptHashData(rawHash, (unsigned char*)input, strlen(input), 0); // Extract the hash data // NOTE: This call could (potentially) fail and this should be checked for DWORD hashLength = 16; //(MD5 length) unsigned char* hashData = new unsigned char[hashLength]; CryptGetHashParam(rawHash, HP_HASHVAL, hashData, &hashLength, 0); // Create a hex-encoded string of the hash bytes char lut[] = { ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ }; char* hash = new char[33]; for(int i = 0; i < 16; i++) { hash[2 * i] = lut[(hashData[i] & 0xF0) >> 4]; hash[2 * i + 1] = lut[hashData[i] & 0x0F]; } hash[32] = ‘\0’; // After processing, cryptoProvider and hasher must be released. if(rawHash) { CryptDestroyHash(rawHash); } if(cryptoProvider) { CryptReleaseContext(cryptoProvider, 0); } delete[] hashData; return hash; } void init_winsock(void) { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup( wVersionRequested, &wsaData ); if(err != 0) { fprintf(stderr, “no winsock was found\n”); exit(EXIT_FAILURE); } /* Check that the Winsock version installed is of a high-enough version. */ if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); fprintf(stderr, “no suitable winsock was available\n”); exit(EXIT_FAILURE); } }]]>

Web Service (SOAP/XML)

The code sample shows the sending of a message to a single mobile number using the .  To send to more than one mobile telephone at a time, separate each mobile number in 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 0 ) && ( result[ 0 ].success ) ) outcome.Text = “Success”; else outcome.Text = “Fail”;]]>