How to Check Alexa Rank in Java


Through this example, we will learn how to get Alexa rank in Java.

Source Code

package com.beginner.examples;

import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AlexaRankExample {

    public static void main(String[] args){
    	int rank = 0;
    	String domain = "csdn.com";
		String url = "http://data.alexa.com/data?cli=10&url=" + domain;

		try 
		{
			URLConnection connect = new URL(url).openConnection();	
			
			Document doc = DocumentBuilderFactory.newInstance()
			.newDocumentBuilder().parse(connect.getInputStream());

			NodeList nodes = doc.getDocumentElement().getElementsByTagName("POPULARITY");
			if (nodes.getLength() > 0) 
			{
				Element element = (Element) nodes.item(0);
				rank = Integer.parseInt(element.getAttribute("TEXT"));
			}

		} 
		catch (Exception e) 
		{
			System.out.println(e.getMessage());
		}
		System.out.println("Rank is : " + rank);
    }
}

Output:

Rank is : 582277

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments