Code Examples (HTTP)

package com.mymobileapi.sample;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * SampleCreditChecker is an example that demonstrates how to connect to 
 * MyMobileApi. It by no means is a complete and robust solution and should not
 * be used in any production code.
 */
public class SampleCreditChecker {

	public static final String MY_MOBILE_API_URL = 
		"https://legacy.mymobileapi.com/api5/http5.aspx?";
	private URLConnection urlConnection;
	
	/**
	 * Initializes a new SampleCreditChecker which will check the number of 
	 * credits available for a given username and password.
	 * 
	 * @param urlConnection	A URLConnection containing a URL to the API.
	 */
	public SampleCreditChecker(URLConnection urlConnection) {
		this.urlConnection = urlConnection;
	}
	
	/**
	 * Gets the number of credits available for the specified username and 
	 * password.
	 * 
	 * @param username	The username.
	 * @param password	The password for the username.
	 * @return			A integer value indicating how many credits the user has
	 * @throws Exception 
	 */
	public int getCredits(String username, String password) throws Exception {
		try {
			//Set DoInput to true so that we can write to the server.
			urlConnection.setDoInput(true);
			//Set DoOutput to true so that we can read from the server.
			urlConnection.setDoOutput(true);
			
			//Create a writer to the server.
			OutputStream raw = urlConnection.getOutputStream();
			OutputStream buffered = new BufferedOutputStream(raw);
			OutputStreamWriter writer = new OutputStreamWriter(buffered, 
					"8859_1");
			
			//Write the following to the server via the URL.
			writer.write("type=credits&username=" + username 
					+ "&password=" + password);
			
			//Don't forget to flush and close the writer.
			writer.flush();
			writer.close();
			
			//Parse the returned XML. Use the InputStream from the connection.
			return parseXmlForCredits(urlConnection.getInputStream());
		} catch (ParserConfigurationException e) {
			System.out.println("Parser Configuration Exception");
			e.printStackTrace();
		} catch (SAXException e) {
			System.out.println("SAX Exception");
			e.printStackTrace();
		}
		return -1;
	}
	
	private int parseXmlForCredits(InputStream stream) 
	throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(stream);
		
		//First check if there are any errors.
		NodeList errors = document.getElementsByTagName("error");
		if (errors.getLength() > 0) {
			Node errorNode = errors.item(0);
			String errorMsg = errorNode.getTextContent();
			if (!errorMsg.isEmpty()) 
				throw new Exception("Error getting credits. " + errorMsg);
		}
		
		//Now check for the number of credits.
		NodeList nodes = document.getElementsByTagName("credits");
		Node creditNode = nodes.item(0);
		return Integer.parseInt(creditNode.getTextContent());
	}
	
	/**
	 * Main entry point for sample.
	 * 
	 * @param args	Command line arguments.
	 */
	public static void main(String[] args) {
		URL url;
		try {
			url = new URL(MY_MOBILE_API_URL);
			URLConnection urlConnection = url.openConnection();
			SampleCreditChecker client = new SampleCreditChecker(urlConnection);
			
			//Please note that xxx and yyy are NOT real usernames and passwords
			//Susbsitute your own username and password.
			int nrCredits = client.getCredits("xxx", "yyy");
			System.out.println("Number of credits = " + nrCredits);
		} catch (MalformedURLException me) {
			System.out.println("The URL is malformed. " + MY_MOBILE_API_URL);
			me.printStackTrace();
		} catch (IOException ioe) {
			System.out.println("An IO Exception has occured.");
			ioe.printStackTrace();
		} catch (Exception e) {
			System.out.append(e.getMessage());
			e.printStackTrace();
		}
	}
}
<?php
    
class MyMobileAPI
{

    public function __construct() {
        $this->url = 'http://mymobileapi.com/api5/http5.aspx';
        $this->username = 'someusername'; //your login username
        $this->password = 'somepassword'; //your login password
      	$this->time = '16:20';
				$this->validityperiod = '24';
    }
    
    public function checkCredits() {
        $data = array(
            'Type' => 'credits', 
            'Username' => $this->username,
            'Password' => $this->password
        );
        $response = $this->querySmsServer($data);
        // NULL response only if connection to sms server failed or timed out
        if ($response == NULL) {
            return '???';
        } elseif ($response->call_result->result) {
	    echo '</br>Credits: ' .  $response->data->credits;
            return $response->data->credits;
        }
    }
    
   public function sendSms($mobile_number, $msg) {
        $data = array(
            'Type' => 'sendparam', 
            'Username' => $this->username,
            'Password' => $this->password,
            'numto' => $mobile_number, //phone numbers (can be comma seperated)
            'data1' => $msg, //your sms message
          	'time' => $this->time, //the time your message will go out
	   				'validityperiod' => $this->validityperiod, //the duration of validity

        );
        $response = $this->querySmsServer($data);
        return $this->returnResult($response);
    }
    
    // query API server and return response in object format
    private function querySmsServer($data, $optional_headers = null) {

        $ch = curl_init($this->url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // prevent large delays in PHP execution by setting timeouts while connecting and querying the 3rd party server
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2000); // response wait time
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 2000); // output response time
        $response = curl_exec($ch);
        if (!$response) return NULL;
        else return new SimpleXMLElement($response);
    }

    // handle sms server response
    private function returnResult($response) {
        $return = new StdClass();
        $return->pass = NULL;
        $return->msg = '';
        if ($response == NULL) {
            $return->pass = FALSE;
            $return->msg = 'SMS connection error.';
        } elseif ($response->call_result->result) {
            $return->pass = 'CallResult: '.TRUE . '</br>';
	    $return->msg = 'EventId: '.$response->send_info->eventid .'</br>Error: '.$response->call_result->error;
        } else {
            $return->pass = 'CallResult: '.FALSE. '</br>';
            $return->msg = 'Error: '.$response->call_result->error;
        }
	echo $return->pass; 
	echo $return->msg; 
        return $return; 
    }
    
}


//Execute script
$test = new MyMobileAPI();
$test->sendSms('0213456789','Test Message'); //Send SMS
$test->checkcredits(); //Check your credit balance


?>