Question

I am trying to send sms via way2sms using HttpComponents. So far the login attempt to the site is successful, as the login history of the website clearly shows it and I am able to get the JSESSIONID successfully from the cookie. However the code somehow fails to send the sms itself. Instead, the response to the final POST request is the HTML page showing the blank text fields for msg and receiver's number. Please let me know where am I going wrong? Here is my code with username and password omitted for obvious reasons:

import java.io.*;
import java.util.ArrayList;
import java.util.List;
//import java.util.regex.*;
//import java.net.*;
//import java.util.Vector;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.*;
import org.apache.http.impl.client.*;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.protocol.ClientContext;
/*import org.apache.http.client.entity.*;
import org.apache.http.client.utils.*;*/
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.*;
import org.apache.http.cookie.params.*;

public class way2
{
    public static void main(String args[]) throws IOException {

    System.out.println("1");
    String url;
    String temp;
    String msg="If you get this msg plz fwd to Harsh";
    CookieStore MycookieStore;
    String cookiename=null;String cookievalue=null;


    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,"UTF-8");
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1");
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY );
    httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,false);
    // Prepare a request object for getting session id
    url="http://site5.way2sms.com/content/index.html";
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(final HttpRequest request,final HttpContext context) throws HttpException, IOException 
        {

        if (!request.containsHeader("Accept")) {
            request.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        }
        if (!request.containsHeader("Accept-Encoding")) {
            request.addHeader("Accept-Encoding", "gzip, deflate");
        }
        if (!request.containsHeader("DNT")) {
            request.addHeader("DNT", "1");
        }
        if (!request.containsHeader("Connection")) {
            request.addHeader("Connection", "keep-alive");
        }
        }

    });
    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {


        public void process(
            final HttpResponse response, 
            final HttpContext context) throws HttpException, IOException {
        HttpEntity entity = response.getEntity();
        Header ceheader = entity.getContentEncoding();
        if (ceheader != null) {
            HeaderElement[] codecs = ceheader.getElements();
            for (int i = 0; i < codecs.length; i++) {
            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                response.setEntity(
                    new GzipDecompressingEntity(response.getEntity())); 
                return;
            }
            }
        }
        }

    });

    HttpGet httpget = new HttpGet(url);
    System.out.println(httpget.getAllHeaders());
    System.out.println("1.2");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);
    System.out.println("2");

    // Examine the response status
    System.out.println(response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();
    System.out.println("3");
    if (entity != null) {

        try {

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(entity.getContent()));



        } catch (IOException ex) {

        throw ex;

        } catch (RuntimeException ex) {

        httpget.abort();
        throw ex;

        }
        EntityUtils.consume(entity);
    }
    //GET request over

    //START OF Code for automatic login and storing cookies
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "********"));
    nvps.add(new BasicNameValuePair("password","********"));
    nvps.add(new BasicNameValuePair("button","Login"));

    url = "http://site5.way2sms.com/Login1.action";
    HttpPost httppost= new HttpPost(url);
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));

    response = httpclient.execute(httppost);
    entity = response.getEntity();

    BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));

    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }

    EntityUtils.consume(entity);
    MycookieStore = httpclient.getCookieStore();
    List<Cookie> Mycookies = MycookieStore.getCookies();
    ClientCookie ck=null; 
    httpclient.setCookieStore(MycookieStore);
    if (Mycookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < Mycookies.size(); i++) {
        ck=(ClientCookie) Mycookies.get(i);
        System.out.println("-hola " + ck.toString());
        System.out.println("-hola " + ck.getComment());
        System.out.println("-hola " + ck.getCommentURL());
        System.out.println("-hola " + ck.getDomain());
        System.out.println("-hola " + ck.getName());
        cookiename = ck.getName();
        cookievalue = ck.getValue();
        System.out.println("-hola " + ck.getPath());
        System.out.println("-hola " + ck.getValue());
        }
    }

    //END OF Code for automatic login  and storing cookies
    //WAY2SMS lets you login till this point
    //get unique id now

    url = "http://site5.way2sms.com/quicksms.action";
    List<NameValuePair> nvps1 = new ArrayList<NameValuePair>();
    nvps1.add(new BasicNameValuePair("HiddenAction", "instantsms"));             
    nvps1.add(new BasicNameValuePair("catnamedis","Birthday"));
    nvps1.add(new BasicNameValuePair("Action","sa65sdf656fdfd"));
    nvps1.add(new BasicNameValuePair("chkall","on"));
    nvps1.add(new BasicNameValuePair("MobNo","*********"));
    nvps1.add(new BasicNameValuePair("textArea",msg));
    nvps1.add(new BasicNameValuePair("bulidguid","username"));
    nvps1.add(new BasicNameValuePair("bulidgpwd","*******"));
    nvps1.add(new BasicNameValuePair("bulidyuid","username"));
    nvps1.add(new BasicNameValuePair("bulidypwd","*******"));
    nvps1.add(new BasicNameValuePair("guid1","username"));
    nvps1.add(new BasicNameValuePair("gpwd1","*******"));
    nvps1.add(new BasicNameValuePair("yuid1","username"));
    nvps1.add(new BasicNameValuePair("ypwd1","*******"));
    nvps1.add(new BasicNameValuePair("button","Send SMS"));

    url = "http://site5.way2sms.com/quicksms.action";
    //url="http://site5.way2sms.com/jsp/InstantSMS.jsp";
    HttpGet sendsms= new HttpGet(url);
    sendsms.addHeader("Content-Type", "application/x-www-form-urlencoded");
    sendsms.addHeader("Referer", "http://site5.way2sms.com/jsp/InstantSMS.jsp");
//  sendsms.setEntity(new UrlEncodedFormEntity(nvps1, HTTP.ISO_8859_1));
    sendsms.setHeader("Cookie", ck.getName()+"="+ck.getValue());
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, MycookieStore);

    response = httpclient.execute(sendsms, localContext);


    entity = response.getEntity();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    EntityUtils.consume(entity);


    httpclient.getConnectionManager().shutdown();
    System.out.println("1");

    }

}

I am using the following PHP code as a reference. This code works perfectly:

<html> 
<body>
<?php 
 function send_sms($userID,$userPWD,$recerverNO,$message)
{
     if(strlen($message)>140) // check for message length
     {echo "message length exceeds 140 characters" ; exit(); }

     $message_urlencode=rawurlencode($message); // message converted into URL encoded form
     $cookie_file_path ="/var/www/cookie.txt";
    // Cookie file location in your machine with full read and write permission

//START OF Code for getting sessionid
    $url="http://site5.way2sms.com/content/index.html";
    $header_array[0] = "GET /content/index.html HTTP/1.1";
    $header_array[1]= "Host: site5.way2sms.com";
    $header_array[2]= "User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
    $header_array[3]= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $header_array[4]= "Accept-Language: en-us,en;q=0.5";
    $header_array[5]= "Accept-Encoding: gzip,deflate";
    $header_array[6]= "DNT: 1";
    $header_array[7] = "Connection: keep-alive";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
    curl_setopt($ch, CURLOPT_REFERER, $reffer);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    $result = curl_exec ($ch);
    curl_close ($ch);
//END OF Code for getting sessionid

//START OF Code for automatic login and storing cookies
    $post_data = "username=".$userID."&password=".$userPWD."&button=Login";
    $url = "http://site5.way2sms.com/Login1.action";
    $header_array[0]="POST /Login1.action HTTP/1.1";
    $header_array[1]="Host: site5.way2sms.com";
    $header_array[2]="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
    $header_array[3]="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $header_array[4]="Accept-Language: en-us,en;q=0.5";
    $header_array[5]="Accept-Encoding: gzip, deflate";
    $header_array[6]="DNT: 1";
    $header_array[7]="Connection: keep-alive";
    $header_array[8]="Content-Type: application/x-www-form-urlencoded";
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt($ch,CURLOPT_REFERER,"http://site5.way2sms.com/content/index.html");
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ($ch);
//END OF Code for automatic login  and storing cookies

// START OF Code is  getting way2sms unique user ID
    $url = "http://site5.way2sms.com/jsp/InstantSMS.jsp";
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $content = curl_exec($ch);
    curl_close ($ch);
    $regex = '/input type="hidden" name="Action" id="Action" value="(.*)"/';
    preg_match($regex,$content,$match);
    $userID = $match[1];
    echo $userID ;
// END OF Code for getting way2sms unique user ID

// START OF Code for sending SMS to Recever
    $post_data = "HiddenAction=instantsms&catnamedis=Birthday&Action=".$userID."&chkall=on&MobNo=".$recerverNO."&textArea=".$message_urlencode."&bulidguid=username&bulidgpwd=*******&bulidyuid=username&bulidypwd=*******&guid1=username&gpwd1=*******&yuid1=username&ypwd1=*******";
    $url = "http://site5.way2sms.com/quicksms.action";
    $header_array[0]="POST /quicksms.action HTTP/1.1";
    $header_array[1]="Host: site5.way2sms.com";
    $header_array[2]="User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
    $header_array[3]="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $header_array[4]="Accept-Language: en-us,en;q=0.5";
    $header_array[5]="Accept-Encoding: gzip, deflate";
    $header_array[6]="DNT: 1";
    $header_array[7]="Connection: keep-alive";
    $header_array[8]="Content-Type: application/x-www-form-urlencoded";
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
   curl_setopt($ch,CURLOPT_REFERER,"Referer: http://site5.way2sms.com/jsp/InstantSMS.jsp");
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ($ch);
// END OF Code for sending SMS to Recever


}// end function send_sms

send_sms("uname","psswd","target mobile no","message");
 ?> 
</body>
</html>

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top