IP 2 Location in Java

This class shows you how to capture some information including IP, Zip code, ISP and ... using screen scraping technique.

This class is based on the service: www.ip2location.com

IP2Location class
package com.blogspot.codetoearn;

import java.io.IOException;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * This class is based on http://www.ip2location.com/ and uses a screen scraping
 * technique to capture the information. And always uses the current IP address
 * of the machine. The syntax is based on JDK 7. and uses JSOUP library:
 * http://jsoup.org/ Please note that any change in the layout of
 * www.ip2location.com home page will make troubles for this class.
 *
 * @author ehsun7b
 */
public class IP2Location extends Observable implements Runnable {

  private HashMap information;

  public IP2Location() {
    information = new HashMap<>();
  }

  @Override
  public void run() {
    try {
      Document doc = Jsoup.connect("http://www.ip2location.com/").get();
      Elements elements = doc.select("table.table");
      if (!elements.isEmpty()) {
        Element table = elements.get(0);
        elements = table.select("tbody");
        if (!elements.isEmpty()) {
          Element tbody = elements.get(0);
          Elements lbls = tbody.select("label");

          for (int i = 0; i < lbls.size(); i += 2) {
            Element lblKey = lbls.get(i);
            Element lblValue = lbls.get(i + 1);
            
            String key = lblKey.text();
            String value = lblValue.text();
            
            information.put(key, value);
          }
        }
      }

      setChanged();
      notifyObservers(information);
    } catch (IOException ex) {
      setChanged();
      notifyObservers(ex);
    }
  }

  public static void main(String[] args) {
    IP2Location ip2Location = new IP2Location();
    ip2Location.addObserver(new Observer() {

      @Override
      public void update(Observable o, Object arg) {
        if (arg instanceof HashMap) {
          HashMap result = (HashMap) arg;
          Set keySet = result.keySet();
          for (String key : keySet) {
            String value = result.get(key);
            System.out.println(key + ": " + value);
          }
        }
      }
    });
    
    Thread t = new Thread(ip2Location);    
    t.start();    
  }
}

Note that any change in the layout of the IP2Location website may cause some bug in this code.

Download the IP2Location class here!

No comments:

Post a Comment