In this example, we show you how to use Java and DOM XML parser to get the Alexa ranking from below the undocumented API :
http://data.alexa.com/data?cli=10&url=domainName
1. Alexa API
For example, type following URL in your browser :
http://data.alexa.com/data?cli=10&url=mkyong.com
Alexa will return back following XML result :
<ALEXA VER="0.9" URL="mkyong.com/" HOME="0" AID="=">
<DMOZ>
<SITE BASE="mkyong.com/"
TITLE="J2EE Web Development"
DESC="Java / J2EE Web Development Tutorials,
which involve Spring, Hibernate, Struts, Maven, jUnit, TestNG, jQuery...">
<CATS/>
</SITE>
</DMOZ>
<SD>
<POPULARITY URL="mkyong.com/" TEXT="10720" SOURCE="panel"/>
<REACH RANK="7924"/>
<RANK DELTA="+600"/>
<COUNTRY CODE="IN" NAME="India" RANK="3542"/>
</SD>
</ALEXA>
Refer to the element “POPULARITY“, the value of “TEXT” attribute is the Alexa ranking.
2. Java, DOM and Alexa API
In Java, just send a normal HTTP request to the API, and use XML parser to get the Alexa ranking.
AlexaSEO.java
package com.mkyong.seo;
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 AlexaSEO {
public static void main(String[] args) {
AlexaSEO obj = new AlexaSEO();
System.out.println("Ranking : " + obj.getAlexaRanking("mkyong.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;
}
}
Result :
Ranking : 10720
My website mkyong.com is ranked 10720 in Alexa, not bad.
hey guys , so i was wondering how exactly i can retrieve 100 sites by given country ? how should the url look like ?
Great post!
Hi, Do you have url & xml format to get top 10 sites in particular country?
lol@”My website mkyong.com is ranked 10720 in Alexa, not bad.” a bit of an understatement there yong! 🙂 Good Job. I was going to post an article on how to do this in Google app engine + python etc.
Nice tutorial . Thankyou 🙂
Thanks 🙂
This API returns more data!
http://data.alexa.com/data?cli=10&dat=snbamz&url=mkyong.com
I have tried this example in my local ,its giving me ranked 0.Please explain why its happening…
Your site might probably be a new one or it is not ranked by Google till the date.