Monday, 28 January 2013

Get the website ranking using Alexa API in Java

Using DOM Parser and Alexa API
You have to send a normal HTTP request to the Alexa API, and by using DOM XML parser to get the Alexa ranking of any web site. Here I am referring to my own web site and the ranking is not so good :). Refer the below code snippet for your reference.

package com.sanjeetpandey;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
public class AlexaRanking {
 
	public static void main(String[] args) {
 
	AlexaSEO obj = new AlexaSEO();
	System.out.println("Ranking is ::: " + obj.getAlexaRanking("sanjeetpandey.com"));
 
	}
 
	public int getAlexaRanking(String domain) {
 
	int result = 0;
	String url = "http://data.alexa.com/data?cli=10&url=" + domain;
 
	try {
	URLConnection conn = new URL(url).openConnection();
	InputStream is = conn.getInputStream();
 
	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	Document doc = dBuilder.parse(is);
	Element element = doc.getDocumentElement();
	NodeList nodeList = element.getElementsByTagName("POPULARITY");
	if (nodeList.getLength() > 0) {
	Element elementAttribute = (Element) nodeList.item(0);
	String ranking = elementAttribute.getAttribute("TEXT")
		if(!"".equals(ranking)){
			result = Integer.valueOf(ranking);
		}
	}
 
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
 
	return result;
}
}

Output -
Ranking is ::: 123123

1 comment: