Welcome to my blog, hope you enjoy reading
RSS

Monday 6 May 2013

SENDING FREE SMS USING JAVA

SENDING FREE SMS USING JAVA


PRE-REQUISTIES

To leverage one of these services, you need to create an account with them. For the purpose of this blog we will be using fullonsms. Create an account into the website. 
For demo purpose we will assume that mobile number /username of account is DEMO_USER and password is DEMO_PASSWORD.


SYSTEM-REQUIREMENTS

Here are some pre-requisites before you can start hacking the code.The code here has been tested with
  1. Java version "1.7.0_17"
  2. Apache HttpComponents Jar ( Download).


We believe that code will work with all versions >= Java 1.5


Before we start hacking the code for sending sms it might be a good idea to understand how it works.
For explaining we assume we are trying to send a sms with some message (TARGET_MESSAGE) to some number (TARGET_NUMBER).

How does this service works:
  1. Log-in to your accoun
  2. Send TARGET_MESSAGE to TARGET_NUMBER
  3. Log-out of your account
    That seems fairly easy. Yes it is …… J

Our objective is to WAP which will implement these three functions.
Before we start writing functions, let us create a project and include all the Jar files that we downloaded from Apache HttpComponents into the BUILD_PATH of the project.

Remember not including these JARs will result into compilation error

 Create a class let us call it FullOnSMS

 Let us declare some class variables :

        // Will be used in Step 1 to login
private final String LOGIN_URL    = "http://fullonsms.com/login.php";

        // Will be used in Step 2 to send SMS
        private final String SEND_SMS_URL = "http://fullonsms.com/home.php";

        // Will be used in Step 3 to logout
private final String LOGOUT_URL = "http://fullonsms.com/logout.php?LogOut=1";
We will use these three URLs to create three requests and process them. To execute these requests we need a client of DefaultHttpClient
  private DefaultHttpClient httpclient;

We also need two more variables  to access our account
     private String mobileNo;
     private String password;

Lets us declare constructor to initialize user account credentials and httpclient


FullOnSMS(String username,String password){
this.mobileNo = username;
this.password = password;
httpclient = new DefaultHttpClient();
}

STEP 1: Now let us start creating the first service to log-in


public boolean isLoggedIn() throws IOException {

// User Credentials on Login page are sent using POST

// So create httpost object

HttpPost httpost = new HttpPost(LOGIN_URL);


// Add post variables to login url

List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("MobileNoLogin", mobileNo));

nvps.add(new BasicNameValuePair("LoginPassword", password));

httpost.setEntity(new UrlEncodedFormEntity(nvps));
// Execute request
HttpResponse response = this.httpclient.execute(httpost);
//Check response entity
HttpEntity entity = response.getEntity();
                if (entity != null) {
                      return true;
                }
return false;
}

STEP 2: Now let us use this http client to send message


        public boolean sendSMS(String toMobile,String message) throws IOException {

                //Use SEND_SMS_URL to create POST object

HttpPost httpost = new HttpPost(SEND_SMS_URL);

                // Add parameters TARGET_MOBILE and TARGET_MESSAGE

List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("MobileNos", toMobile));

                nvps.add(new BasicNameValuePair("Message", message));

        

                httpost.setEntity(new UrlEncodedFormEntity(nvps));

                //Execute Request
HttpResponse response = this.httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
if(entity != null) {
return true;
}
return false;
}

STEP 3: Now let us use this http client to logout from our client


         public boolean logoutSMS() throws IOException {

                // This a simple GET request parameters are passed in URL itself

HttpGet httpGet = new HttpGet(LOGOUT_URL);

HttpResponse response;

response = this.httpclient.execute(httpGet);

HttpEntity entity = response.getEntity();

if (entity != null) {
return true;

}
return false;
}


FULL SOURCE CODE


package com.sms.india;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class FullOnSMS {
 
 private final String LOGIN_URL    = "http://fullonsms.com/login.php";
 private final String SEND_SMS_URL = "http://fullonsms.com/home.php";
 private final String LOGOUT_URL = "http://fullonsms.com/logout.php?LogOut=1";
 
 private final int MESSAGE_LENGTH = 10;
 private final int MOBILE_NUMBER_LENGTH = 140;
 private final int PASSWORD_LENGTH = 10;

 private String mobileNo;
 private String password;
 private DefaultHttpClient httpclient;
 
 FullOnSMS(String username,String password){
  this.mobileNo = username;
  this.password = password;
  httpclient = new DefaultHttpClient();
 }

 
 public boolean isLoggedIn() throws IOException {
  // User Credentials on Login page are sent using POST
  // So create httpost object
  HttpPost httpost = new HttpPost(LOGIN_URL);
  
  // Add post variables to login url
  List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("MobileNoLogin", mobileNo));
  nvps.add(new BasicNameValuePair("LoginPassword", password));
  httpost.setEntity(new UrlEncodedFormEntity(nvps));
  
  // Execute request
  HttpResponse response = this.httpclient.execute(httpost);
  
  //Check response entity
  HttpEntity entity = response.getEntity();
        if (entity != null) {
            System.out.println("entity " + slurp(entity.getContent(), 10000000));
            System.out.println("entity " + response.getStatusLine().getStatusCode());

         return true;
        }
  return false;
 }

 public boolean sendSMS(String toMobile,String message) throws IOException {
  HttpPost httpost = new HttpPost(SEND_SMS_URL);
  List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("MobileNos", toMobile));
                nvps.add(new BasicNameValuePair("Message", message));
        
                httpost.setEntity(new UrlEncodedFormEntity(nvps));
  HttpResponse response = this.httpclient.execute(httpost);
  HttpEntity entity = response.getEntity();
  if(entity != null) {
                        System.out.println("entity " + slurp(entity.getContent(), 10000000));
                        System.out.println("entity " + response.getStatusLine().getStatusCode());
   return true;
  }
  return false;
 }
 
 public boolean logoutSMS() throws IOException {
  HttpGet httpGet = new HttpGet(LOGOUT_URL);
  HttpResponse response;
  response = this.httpclient.execute(httpGet);
  HttpEntity entity = response.getEntity();
  if (entity != null) {
   System.out
     .println("entity " + slurp(entity.getContent(), 10000000));
   System.out.println("entity "
     + response.getStatusLine().getStatusCode());
   return true;
  }
  return false;
 }
 

 public static String slurp(final InputStream is, final int bufferSize)
 {
   final char[] buffer = new char[bufferSize];
   final StringBuilder out = new StringBuilder();
   try {
     final Reader in = new InputStreamReader(is, "UTF-8");
     try {
       for (;;) {
         int rsz = in.read(buffer, 0, buffer.length);
         if (rsz < 0)
           break;
         out.append(buffer, 0, rsz);
       }
     }
     finally {
       in.close();
     }
   }
   catch (UnsupportedEncodingException ex) {
     /* ... */
   }
   catch (IOException ex) {
       /* ... */
   }
   return out.toString();
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Replace DEMO_USERNAME with username of your account
  String username = "DEMO_USERNAME";
  //Replace DEMO_PASSWORD with password of your account
  String password = "DEMO_PASSWORD";
  //Replace TARGET_MOBILE with a valid mobile number 
  String toMobile = "TARGET_MOBILE";
  
  String toMessage = "Test message from http://cooljapps.blogspot.com";
  
  FullOnSMS fullOnSMS = new FullOnSMS(username, password);
  try{
   if(fullOnSMS.isLoggedIn() && fullOnSMS.sendSMS(toMobile,toMessage)){
    fullOnSMS.logoutSMS();
    System.out.println("Message was sent successfully " );
   }
  }catch(IOException e){
   System.out.println("Unable to send message, possible cause: " + e.getMessage());
  }
 }
}

0 comments: