Tag Archives: webservice

Android – Simple XML DOM Parser Example for Reading Response From InputStream


I am trying to use simple XML DOM Parser for my HTTP response.

Basically I am calling .Net webservice and I need to parse response.

Let me also cover calling the .Net webservice.

Webservice can be called/consumed by may way.
For Example:

Use SOAP call, HTTP Get method, HTTP Post method and many more..

I have one Web service method with Post call structure:

POST /api.asmx/validateCredentials HTTP/1.1
Host: api.mywebsite.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length


Now I want to call it from Android HTTP Post method.
I will also need BasicNameValue pair for sending data to web service URL.

I’ll do it like:

try {
	HttpClient httpClient = new DefaultHttpClient();
	HttpContext localContext = new BasicHttpContext();
	HttpPost httpPost = new HttpPost("http://api.mywebsite.com/api.asmx/validateCredentials");

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

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

	httpPost.setEntity(new UrlEncodedFormEntity(nvps));

	HttpResponse response = httpClient.execute(httpPost, localContext);

} catch (Exception e) {

Now First of all I wanted my response as String.

So I use Buffer reader to read the data from response object.

BufferedReader reader = new BufferedReader(new InputStreamReader(
		response.getEntity().getContent(), "UTF-8"));
StringBuffer responseString = new StringBuffer("");
String line;
while ((line = reader.readLine()) != null) {

Now I can see the response in LogCat.
I get the XML response (in String) as follow:

<?xml version="1.0" encoding="utf-8"?>
<returnMessage xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.myserver.com/">
	<message>User Authenticated</message>
		The user's credentials were valid and is authorized to execute this transaction.
	<userno xsi:type="xsd:double">211</userno>

Here you can see some tags and actually we need those values!!

So I can now use this “String” object to parse the XML.

To parse the XML we have several methods like SAX parser, DOM parser XML pool parser etc.

I heard that SAX parser is best, I had also used that one, But here I will go with Simple DOM parser.

So Instead of getting the response in String as above, I can directly use InputStream for DOM parser.

InputStream in = response.getEntity().getContent();

DocumentBuilder builder = DocumentBuilderFactory.newInstance()
Document doc = builder.parse(in);
String responseCode = "";
String extendedMessage = "";
if (doc != null) {
	NodeList nl = doc.getElementsByTagName("responseCode");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		responseCode = node.getTextContent();
	nl = doc.getElementsByTagName("extendedMessage");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		extendedMessage = node.getTextContent();
System.out.println(responseCode + " " + extendedMessage);

I hope this post can help some one who wants to get started with Android in just 10 minutes!

Calling a FedEx Rate Service from Classic ASP with SOAP call

Hi Friends,

Last month I worked in Classic ASP. I had to prepare a Delivery Calendar.

I consumed a FedEx web service for Rate request.

It can also return delivery commitment details like Delivery Date, Time, date etc.

Basically what I need is to call a web service using SOAP call.

May people find difficulty in Classic ASP, as FexEx is not giving sample code for consuming their web service.

So I decided to post at least on web service call, so that you guys can have idea about how to consume FedEx Web service in Classic ASP.


<% option explicit %>
<!--#include file="FedexAccountInfo.asp"-->
    Dim subscriberzip
    Dim subscribercountry
    Dim ShipmentDate
    Dim xmlReq
    Dim objhttp
    Dim outstr
    Dim NodeList

    subscriberzip = Request.QueryString("zip")
    subscribercountry = "US"
    ShipmentDate = Request.QueryString("date")

    xmlReq = "<?xml version=""1.0"" encoding=""UTF-8""?>" &_
    "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">" &_
    "<soapenv:Body>" &_
    "<RateRequest xmlns=""http://fedex.com/ws/rate/v9"">" &_
    "<WebAuthenticationDetail>" &_
    "<UserCredential>" &_
    "<Key>" & FedExkey & "</Key>" &_
    "<Password>" & FedExPassword & "</Password>" &_
    "</UserCredential>" &_
    "</WebAuthenticationDetail>" &_
    "<ClientDetail>" &_
    "<AccountNumber>" & FedExAccountNumber & "</AccountNumber>" &_
    "<MeterNumber>" & FedExMeterNumber & "</MeterNumber>" &_
    "</ClientDetail>" &_
    "<TransactionDetail>" &_
    "<CustomerTransactionId>TEST</CustomerTransactionId>" &_
    "</TransactionDetail>" &_
    "<Version>" &_
    "<ServiceId>crs</ServiceId>" &_
    "<Major>9</Major>" &_
    "<Intermediate>0</Intermediate>" &_
    "<Minor>0</Minor>" &_
    "</Version>" &_
    "<ReturnTransitAndCommit>1</ReturnTransitAndCommit>" &_
    "<CarrierCodes>FDXE</CarrierCodes>" &_
    "<VariableOptions>SATURDAY_DELIVERY</VariableOptions>" &_
    "<RequestedShipment>" &_
    "<ShipTimestamp>" & ShipmentDate & "T09:00:00-00:00</ShipTimestamp>" &_
    "<DropoffType>REGULAR_PICKUP</DropoffType>" &_
    "<PackagingType>YOUR_PACKAGING</PackagingType>" &_
    "<Shipper>" &_
    "<Address>" &_
    "<PostalCode>96790</PostalCode>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Address>" &_
    "</Shipper>" &_
    "<Recipient>" &_
    "<Address>" &_
    "<PostalCode>" & subscriberzip & "</PostalCode>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Address>" &_
    "</Recipient>" &_
    "<ShippingChargesPayment>" &_
    "<PaymentType>SENDER</PaymentType>" &_
    "<Payor>" &_
    "<AccountNumber>" & FedExAccountNumber & "</AccountNumber>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Payor>" &_
    "</ShippingChargesPayment>" &_
    "<RateRequestTypes>LIST</RateRequestTypes>" &_
    "<PackageCount>1</PackageCount>" &_
    "<PackageDetail>INDIVIDUAL_PACKAGES</PackageDetail>" &_
    "<RequestedPackageLineItems>" &_
    "<SequenceNumber>1</SequenceNumber>" &_
    "<Weight>" &_
    "<Units>LB</Units>" &_
    "<Value>10.0</Value>" &_
    "</Weight>" &_
    "</RequestedPackageLineItems>" &_
    "</RequestedShipment>" &_
    "</RateRequest>" &_
    "</soapenv:Body>" &_

    set objHttp = Server.createobject("Msxml2.ServerXMLHTTP")

    'For live
    objHttp.open "POST", https://gateway.fedex.com:443/web-services/rate, false

    'For test
    'objHttp.open "POST", https://gatewaybeta.fedex.com:443/web-services/rate, false

    OBJHTTP.setRequestHeader "Referer", "Your Company name"
    OBJHTTP.setRequestHeader "Host", "wsbeta.fedex.com"
    OBJHTTP.setRequestHeader "Accept", "image/gif, image/jpeg,image/pjpeg, text/plain, text/html, */*"
    OBJHTTP.setRequestHeader "Content-Type", "image/gif"
    OBJHTTP.setRequestHeader "Content-Length", cstr(len(xmlReq))

    objHttp.Send xmlReq

    outstr = objHttp.responseText

    dim objDoc, i, j, status
    Set objDoc = CreateObject("Microsoft.XMLDOM")
    objDoc.async = False

'    Response.Write objDoc.getElementsByTagName("v9:HighestSeverity")(0).text

    Set NodeList = objDoc.getElementsByTagName("v9:RateReplyDetails")

    for i=0 to (NodeList.length-1)
'        for j=0 to (NodeList(0).childNodes.length-1)
'            if Trim(NodeList(i).childNodes(j).nodename) = "v9:ServiceType" then
'                Response.write "ServiceType: " & Trim(NodeList(i).childNodes(j).text) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DeliveryDayOfWeek" then
'                Response.write "Day: " & Trim(NodeList(i).childNodes(j).text) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DeliveryTimestamp" then
'                Response.write "Date: " & left(Trim(NodeList(i).childNodes(j).text), 10) & "<br/>"
'                Response.write "Time: " & right(Trim(NodeList(i).childNodes(j).text), 8) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DestinationServiceArea" then
'                Response.write "Area: " & Trim(NodeList(i).childNodes(j).text) & "<br/><br/>"
'            end if
'        next

    if Len(outstr) = 0 then
        Response.write "<br/> Error: Unable to communicate with Fedex Server. Please check your Internet connection.<br/>"
        Response.Write outstr
    end if

Now run this page in Internet Explorer and you will see the response in XML.

ListView like Android Market Application with separator and ColdFusion as web server

Hi folks. This time I’m presenting a huge post.

This post will cover following things:

  • ListView with separator
  • Pagination  like Android Market application

I know that not all of you knows ColdFusion and its component (cfc), but it is just a server part like your web service code.


<cfcomponent displayname="myWebservice">
	<cffunction name="getJobs" access="remote" output="false" returntype="struct">
		<cfargument name="currentPage" required="true" type="numeric" default='1' />
		<cfargument name="totalRecord" required="true" type="numeric" default="10" />
		<cfargument name="searchString" required="false" type="string" default="" />
		<cfset var qResult = "">
		<cfset var condition = "" />
		<cfset var startRow = (arguments.CurrentPage-1) * arguments.TotalRecord +1 />
		<cfset var endRow = startRow + arguments.TotalRecord -1 />
		<cfset var qGetAllRecord = "" />
		<cfset var gridStruct = "" />
		<cfif len(arguments.searchString)>
			<cfset condition = condition & " -- your search conditions goes here" />
		<cfstoredproc procedure="usp_Pagination" datasource="#application.DSN#" username="#application.DBUID#" password="#application.DBPWD#">
			<cfprocresult name="qGetAllRecord" resultset="1">
			<cfprocresult name="qtotalRecord" resultset="2">
			<cfprocparam dbvarname="@SqlColumns" cfsqltype="CF_SQL_VARCHAR" value="*">
			<cfprocparam dbvarname="@SqlFriendlyColumns" cfsqltype="CF_SQL_VARCHAR" value="*">
			<cfprocparam dbvarname="@SqlTableClause" cfsqltype="CF_SQL_VARCHAR" value="Jobs">
			<cfprocparam dbvarname="@StartRow" cfsqltype="CF_SQL_VARCHAR" value="#startRow#">
			<cfprocparam dbvarname="@EndRow" cfsqltype="CF_SQL_VARCHAR" value="#endRow#">
			<cfprocparam dbvarname="@SqlWhere" cfsqltype="CF_SQL_VARCHAR" value="#condition#">
			<cfprocparam dbvarname="@SqlRowNumOrderBy" cfsqltype="CF_SQL_VARCHAR" value="Jobs.createdDate desc">
			<cfprocparam dbvarname="@SqlOuterOrderBy" cfsqltype="CF_SQL_VARCHAR" value="createdDate desc">
		<cfset gridStruct=StructNew() />
		<cfset gridStruct.query = qGetAllRecord />
		<cfset gridStruct.totalRowCount=qtotalRecord.countAll />
		<cfreturn qResult>

The reason behind showing this code is to let you know the implementation of the server part.

In above function, I am returning fix number of records from my database. It is used to pull out ten ten records from a query that has thousands of records.

Now I’m calling this web service like:


And it returns a data in JSON format like:

{“QUERY”:{“COLUMNS”:[“JOBID”,”JOBTITLE”,”CREATEDATE”,”JOBDETAIL”],”DATA”:[[“1″,”Title1″,”January, 25 2011 10:55:53″,”Detail is here”],[“2″,”Title2″,”January, 25 2011 10:55:53″,”Detail is here”],[“3″,”Title3″,”January, 20 2011 14:13:10″,”Detail is here”],[“4″,”Title4″,”January, 20 2011 14:13:10″,”Detail is here”],[“5″,”Title5″,”January, 20 2011 14:13:10″,”Detail is here”],[“6″,”Title6″,”January, 20 2011 14:13:10″,”Detail is here”],[“7″,”Title7″,”January, 18 2011 16:23:28″,”Detail is here”],[“8″,”Title8″,”January, 17 2011 11:22:02″,”Detail is here”],[“9″,”Title9″,”January, 11 2011 09:22:32″,”Detail is here”],[“10″,”Title10″,”January, 11 2011 09:22:32″,”Detail is here”]]},”TOTALROWCOUNT”:”120″}

Now we are ready to build Android app.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 <EditText android:id="@+id/JobSearch"
	<ListView android:id="@+id/JobList"
		android:layout_height="wrap_content" />
	<TextView android:id="@+id/EmptyJobList" android:layout_width="fill_parent"
		android:layout_height="fill_parent" android:text="No Results" android:visibility="invisible" />


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	<TextView android:id="@+id/JobDate" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:gravity="center"
		style="?android:attr/listSeparatorTextViewStyle" />


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="wrap_content" android:paddingRight="5px">
	<TextView android:id="@+id/JobTitle" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_alignParentLeft="true"
		android:text="jobTitle" style="?android:attr/textAppearanceLarge" />
	<TextView android:id="@+id/JobDetail"
		android:layout_width="fill_parent" android:layout_height="wrap_content" />

And MyJobListView.java

package com.isummation.listview;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeSet;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyListView extends Activity {
	private static boolean isInitialized;
	private static int JOBID_IDX;
	private static int JOBTITLE_IDX;
	private static int CREATEDDATE_IDX;
	private static int JOBDETAIL_IDX;
	private JobListAdapter jobListAdapter;
	private long TotalRowCount;
	private int totalRecordPerCall = 20;
	private Date lastDate;
	private EditText JobSearch;
	private ListView list;

	class JobListRowData {
		boolean isHeader;
		Date jobCreationDate;
		int jobId;
		String jobTitle;
		String jobDetail;

	class JobListAdapter extends BaseAdapter {
		private static final int TYPE_ITEM = 0;
		private static final int TYPE_SEPARATOR = 1;
		private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
		private LayoutInflater mInflater;
		private ArrayList mData = new ArrayList();
		private TreeSet mSeparatorsSet = new TreeSet();
		private int count = 0;
		private boolean isCleared = true;

		public JobListAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		public void ParseJSONArray(JSONArray JQueryData) {
			int len = JQueryData.length();

			final TextView EmptyListView = (TextView) findViewById(R.id.EmptyJobList);

			if (TotalRowCount == 0) {
			} else {
			try {
				for (int i = 0; i &lt; len; i++) {

					Date tempDate = new Date(JQueryData.getJSONArray(i)

					if (lastDate == null) {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.isHeader = true;
						jobListRowData.jobCreationDate = new Date(JQueryData.getJSONArray(i)

						jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)

						lastDate = new Date(JQueryData.getJSONArray(i)
					} else if (lastDate.getDate() == tempDate.getDate()
							&amp;&amp; lastDate.getMonth() == tempDate.getMonth()
							&amp;&amp; lastDate.getYear() == tempDate.getYear()) {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)
					} else {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.isHeader = true;
						jobListRowData.jobCreationDate = new Date(JQueryData.getJSONArray(i)
						lastDate = new Date(JQueryData.getJSONArray(i)

						jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)

			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), e.getMessage(),
				Log.e(e.getClass().getName(), e.getMessage(), e);
				TotalRowCount = 0;

		public void initialize() {
			isCleared = false;
			count = 0;
			lastDate = null;
			JSONArray JQueryData = getJobs(1);
			isCleared = true;

		public void addMoreData() {
			if (jobListAdapter.count &lt; TotalRowCount &amp;&amp; isCleared) { 
				JSONArray JQueryData = getJobs((jobListAdapter.count + totalRecordPerCall)
						/ totalRecordPerCall + 1);

		public void addItem(final JobListRowData item) {
			count += 1;

		public void addSeparatorItem(final JobListRowData item) {
			mSeparatorsSet.add(mData.size() - 1);

		public int getItemViewType(int position) {
			return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR
					: TYPE_ITEM;

		public int getViewTypeCount() {
			return TYPE_MAX_COUNT;

		public int getCount() {
			return mData.size();

		public JobListRowData getItem(int pos) {
			return mData.get(pos);

		public long getItemId(int pos) {
			return pos;

		public boolean isEnabled(int position) {
			return mSeparatorsSet.contains(position) ? false : true;

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			int type = getItemViewType(position);
			if (convertView == null) {
				holder = new ViewHolder();
				switch (type) {
				case TYPE_ITEM:
					convertView = mInflater.inflate(R.layout.joblistitem, null);
					holder.text = (TextView) convertView
					holder.text2 = (TextView) convertView
					convertView = mInflater.inflate(R.layout.joblistheader,
					holder.text = (TextView) convertView
			} else {
				holder = (ViewHolder) convertView.getTag();
			switch (type) {
			case TYPE_ITEM:
				try {
									"MMM dd, yyyy",
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
					Log.e(e.getClass().getName(), e.getMessage(), e);
			return convertView;

		class ViewHolder {
			TextView text;
			TextView text2;

	public void onCreate(Bundle savedInstanceState) {

		JobSearch = (EditText) findViewById(R.id.JobSearch);
		JobSearch.setOnKeyListener(new View.OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER
						&amp;&amp; event.getAction() == KeyEvent.ACTION_DOWN) {
				return false;

		jobListAdapter = new JobListAdapter();

		list = (ListView) findViewById(R.id.JobList);
		list.setOnScrollListener(new AbsListView.OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {


			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				boolean loadMore = firstVisibleItem + visibleItemCount &gt;= totalItemCount;
				if (loadMore) {

		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<!--?--> parent, View view,
					int position, long id) {
				JobListRowData item = jobListAdapter.getItem(position);
				if (!item.isHeader) {
					// start another activity

	public JSONArray getJobs(int currentPage) {
		try {
			String searchString = JobSearch.getText().toString();
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpGet httpGet = new HttpGet(
							+ URLEncoder.encode("" + currentPage, "UTF-8")
							+ "&amp;totalRecord="
							+ totalRecordPerCall
							+ "&amp;searchString="
							+ URLEncoder.encode(searchString, "UTF-8"));
			HttpResponse response = httpClient.execute(httpGet, localContext);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse = reader.readLine();
			JSONObject JResponse = new JSONObject(sResponse);
			JSONObject JQuery = JResponse.getJSONObject("QUERY");
			TotalRowCount = JResponse.getLong("TOTALROWCOUNT");
			JSONArray JQueryColumns = JQuery.getJSONArray("COLUMNS");

			if (!isInitialized) {
				int len = JQueryColumns.length();
				for (int i = 0; i &lt; len; i++) {
					if (JQueryColumns.getString(i).equals("JOBID")) {
						JOBID_IDX = i;
					} else if (JQueryColumns.getString(i).equals("JOBTITLE")) {
						JOBTITLE_IDX = i;
					} else if (JQueryColumns.getString(i).equals("CREATEDATE")) {
					} else if (JQueryColumns.getString(i).equals(
							"JOBDETAIL")) {
						JOBDETAIL_IDX = i;
				isInitialized = true;

			return JQuery.getJSONArray("DATA");
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), e.getMessage(),
			Log.e(e.getClass().getName(), e.getMessage(), e);
			return new JSONArray();


I’ve updated above code, for “Loading…” effect while getting next 20 records.
You can now download the source code.
Download source code

SplendidCRM is copy of SugarCRM?


Now a days I’m reviewing all open source CRM. Till now I have seen SugarCRM, vTiger, SplendidCRM etc.

They are also providing web services to integrate our application to CRM.

SpledidCRM is built over Asp.net, so it is but obvious that it’s web service will be in .net.

When I browse it to include it in my sample web site, I surprised!

So Splendid programmer forget to change the name of web service? lol!