Showing posts with label Net. Show all posts
Showing posts with label Net. Show all posts

Monday, October 22, 2012

Get Address Information by IP



Introduction

There are many IP to Address services such like http://www.hostip.info/, http://ip-lookup.net/, http://www.iplocation.net/ and so on, this post will talking about how to get address information by given IP via the API provided by Hostip.info.

Prerequest

The sample of this post is based on http://ben-bai.blogspot.tw/2012/02/java-practice-javanet-practice-use.html

Required jar files:


 json-lib: http://sourceforge.net/projects/json-lib/files/json-lib/
 commons-beanutils-1.8.3.jar http://commons.apache.org/beanutils/download_beanutils.cgi
 commons-collections-3.2.1.jar http://commons.apache.org/collections/download_collections.cgi
 commons-lang-2.5.jar http://commons.apache.org/lang/download_lang.cgi
 commons-logging-1.1.1.jar http://commons.apache.org/logging/download_logging.cgi
 ezmorph-1.0.6.jar http://sourceforge.net/projects/ezmorph/files/ezmorph/



The Program

IPLookupService.java

Get position by given IP and then get formatted address by given lat/lng

package test;

import java.io.InputStreamReader;

import net.sf.json.JSONObject;

/**
 * required jar files:
 * json-lib: http://sourceforge.net/projects/json-lib/files/json-lib/
 * commons-beanutils-1.8.3.jar http://commons.apache.org/beanutils/download_beanutils.cgi
 * commons-collections-3.2.1.jar http://commons.apache.org/collections/download_collections.cgi
 * commons-lang-2.5.jar http://commons.apache.org/lang/download_lang.cgi
 * commons-logging-1.1.1.jar http://commons.apache.org/logging/download_logging.cgi
 * ezmorph-1.0.6.jar http://sourceforge.net/projects/ezmorph/files/ezmorph/
 *
 */
public class IPLookupService {
    public static void main (String[] args) {
        AddressInfo info = ipToLocation("98.76.54.32");
        System.out.println(info.getCountryName());
        System.out.println(info.getCountryCode());
        System.out.println(info.getCity());
        System.out.println(info.getLat());
        System.out.println(info.getLng());
        System.out.println(info.getFormattedAddress());
    }
    /**
     * return country, city, address by given IP
     * @param ip
     * @return
     */
    public static AddressInfo ipToLocation (String ip) {
        String country;
        AddressInfo info = null;
        double lat;
        double lng;
        StringBuilder sb = getResponse(
                "http://api.hostip.info/get_json.php?ip=" + ip + "&position=true");
        JSONObject jobj = JSONObject.fromObject(sb.toString());
        lat = jobj.getDouble("lat");
        lng = jobj.getDouble("lng");
        info = new AddressInfo(jobj.getString("country_name"), jobj.getString("country_code"),
                jobj.getString("city"), lat, lng,
                GeocodeService.getAddressByLatLng(lat, lng, "ja"));
        return info;
    }
    public static StringBuilder getResponse(String path){
        try {
            java.net.URL url = new java.net.URL(path);
            java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
            uc.setRequestProperty("User-agent", "Mozilla/5.0");

            uc.setRequestProperty("Accept-Charset", "UTF-8"); // encoding
            uc.setReadTimeout(30000);// timeout limit
            uc.connect();// connect
            int status = uc.getResponseCode();

            switch (status) {
                case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504 timeout
                    break;
                case java.net.HttpURLConnection.HTTP_FORBIDDEN://403 forbidden
                    break;
                case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500 server error
                    break;
                case java.net.HttpURLConnection.HTTP_NOT_FOUND://404 not exist
                    break;
                case java.net.HttpURLConnection.HTTP_OK: // ok
                    InputStreamReader reader = new InputStreamReader(uc.getInputStream(), "UTF-8");

                    int ch;
                    StringBuilder sb = new StringBuilder("");
                    while((ch = reader.read())!= -1){
                        sb.append((char)ch);
                    }
                    return sb;
            }

        } catch (java.net.MalformedURLException e) { // invalid address format
            e.printStackTrace();
        } catch (java.io.IOException e) { // connection broken
            e.printStackTrace();
        }
        return null;
    }
}
class AddressInfo {
    private String _countryName;
    private String _countryCode;
    private String _city;
    private double _lat;
    private double _lng;
    private String _formattedAddress;
    AddressInfo (String countryName, String countryCode,
        String city, double lat, double lng, String formattedAddress) {
        _countryName = countryName;
        _countryCode = countryCode;
        _city = city;
        _lat = lat;
        _lng = lng;
        _formattedAddress = formattedAddress;
    }
    public String getCountryName () {
        return _countryName;
    }
    public String getCountryCode () {
        return _countryCode;
    }
    public String getCity () {
        return _city;
    }
    public double getLat () {
        return _lat;
    }
    public double getLng () {
        return _lng;
    }
    public String getFormattedAddress () {
        return _formattedAddress;
    }
}


function added to GeocodeService.java

The new function returns formatted address by given lat/lng

    /**
     * return formatted address by given lat/lng
     * @param lat
     * @param lng
     * @param lang
     * @return
     */
    public static String getAddressByLatLng (double lat, double lng, String lang) {
        StringBuilder sb = getResponse("http://maps.googleapis.com/maps/api/geocode/json?"
                + "latlng="+lat+","+lng
                + "&sensor=true&language="+lang);
        JSONObject jobj = JSONObject.fromObject(sb.toString());
        return jobj.getJSONArray("results").getJSONObject(0).getString("formatted_address");
    }


The Result

http://maps.googleapis.com/maps/api/geocode/json?latlng=33.7629,-84.4226&sensor=true&language=ja
UNITED STATES
US
Atlanta, GA
33.7629
-84.4226
1068 Simpson Rd NW, アトランタ ジョージア 30314 アメリカ合衆国


Reference

http://stackoverflow.com/questions/2362413/any-reliable-api-available-to-determine-users-city-and-country-from-ip-address


Download

sample code at github
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Net/src/test/IPLookupService.java
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Net/src/test/GeocodeService.java

Monday, April 9, 2012

Java Simple Web Crawler

Introduction

This is a simple web crawler, it is really simple,
do not have ability to prevent robot detection,
and may not parse link perfectly.

Just use it to do something what a good user will do.

The Program

SimpleCrawler.java


package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * This is a simple web crawler, it is really simple,
 * do not have ability to prevent robot detection,
 * and may not parse link perfectly.
 * 
 * Just use it to do something what a good user will do.
 *
 */
public class SimpleCrawler implements Runnable {
    public static final String DISALLOW = "Disallow:";

    // the result, <url, content>
    private Map<String, String> result = new HashMap<String, String>();
    // the url list to crawl
    private List<String> urlToCrawl = new ArrayList<String>();
    // the url list to skip
    private List<String> badUrls = new ArrayList<String>();
    // The current url object, used to build relative path
    private URL url;
    // the maximum amount of result 0 or smaller denotes no limitation
    private int resultLimit = 0;
    // whether the crawler is stopped
    private boolean stopped = false;

    // the delay between crawl
    private long delayBetweenCrawl = 5000;
    // the delay between check url
    private long delayBetweenCheck = 1000;

    /**
     * Crawl the given url,
     * @param rootUrl The Url to Crawl
     * @param limit The maximum size of result, 0 or negative denotes no limitation
     */
    public void Crawl (String rootUrl, int limit) {
        this.urlToCrawl.add(rootUrl);
        this.resultLimit = limit;
        
        new Thread(this).start();
    }
    public void run () {
        try {
            while (true) {
                if (urlToCrawl.size() == 0) {
                    break;
                }
                String strUrl = urlToCrawl.remove(0);
                url = new java.net.URL(strUrl);
                // get the content of first url
                String content = getResponse(strUrl, url).toString();
                // put the url/content to result map
                if (content != null) {
                    result.put(strUrl, content);
                    // stop
                    if (resultLimit > 0 && result.size() >= resultLimit)
                        break;
                    // get all url that have not be crawled 
                    urlToCrawl.addAll(getSubUrls(content, url));
                }

                // take a rest, do not crawl too fast
                try {
                    Thread.sleep(delayBetweenCrawl);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
            stopped = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * get all html links in the given content
     * @param content The content that crawled by current url
     * @param url the current url
     * @return List, all html links in the given content
     */
    private List<String> getSubUrls (String content, URL url) {
        List<String> subUrls = new ArrayList<String>();
        String lowerCaseContent = content.toLowerCase();
        int index = 0;
        // has anchor tag
        while ((index = lowerCaseContent.indexOf("<a", index)) != -1) {
            // take a rest, do not check too fast
            try {
                Thread.sleep(delayBetweenCheck);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            // has href="..."
            if ((index = lowerCaseContent.indexOf("href", index)) == -1) 
                break;
            if ((index = lowerCaseContent.indexOf("=", index)) == -1) 
                break;

            // get next part of url
            index++;
            String remaining = content.substring(index);
            StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\"<>#");
            String strLink = st.nextToken();
            // shift to the first http if exists
            if (!strLink.startsWith("http") && strLink.contains("http")) {
                strLink = strLink.substring(strLink.indexOf("http"));
            }
            // cut the tail after htm or html
            if ((!strLink.endsWith("html") && strLink.contains("html"))
                || (!strLink.endsWith("htm") && strLink.contains("htm"))) {
                boolean hasHtml = false;
                if (strLink.contains("html")) {
                    strLink = strLink.substring(0, strLink.lastIndexOf("html") + 4);
                    hasHtml = true;
                } else
                    strLink = strLink.substring(0, strLink.lastIndexOf("htm") + 3);
                System.out.println(hasHtml + " modified tail " + strLink);
            }
            if (badUrls.contains(strLink)) {
                System.out.println(" is bad url");
                continue;
            }
            // check to see if this URL has already been 
            // searched or is going to be searched
            if (!result.containsKey(strLink) 
                && !urlToCrawl.contains(strLink)) {

                URL urlLink;
                try {
                    // absolute link
                    if (strLink.startsWith("http"))
                        urlLink = new URL(strLink);
                    else // relative link
                        urlLink = new URL(url, strLink);
                    strLink = urlLink.toString();
                    System.out.println(strLink);
                } catch (MalformedURLException e) {
                    System.out.println("ERROR: bad URL " + strLink);
                    if (!badUrls.contains(strLink)) {
                        badUrls.add(strLink);
                    }
                    continue;
                }
    
                // only look at http links
                if (urlLink.getProtocol().compareTo("http") != 0) {
                    System.out.println("Not http");
                    if (!badUrls.contains(strLink)) {
                        badUrls.add(strLink);
                    }
                    continue;
                }
    
                // test and store the url
                try {
                    // try opening the URL
                    URLConnection urlLinkConnection 
                        = urlLink.openConnection();
                    urlLinkConnection.setAllowUserInteraction(false);
                    InputStream linkStream = urlLink.openStream();
                    String strType
                        = urlLinkConnection.guessContentTypeFromStream(linkStream);
                    String strTypeTwo = urlLinkConnection.getContentType();
                    linkStream.close();
    
                    // is text/html
                    if ((strTypeTwo != null && strTypeTwo.contains("text/html"))
                        || (strType != null && strType.contains("text/html"))) {
                        // add new url to list
                        urlToCrawl.add(strLink);
                    }
                } catch (IOException e) {
                    System.out.println("ERROR: couldn't open URL " + strLink);
                    if (!badUrls.contains(strLink)) {
                        badUrls.add(strLink);
                    }
                    continue;
                }
            }
            // add to bad urls if not added
            if (!result.containsKey(strLink) 
                && !urlToCrawl.contains(strLink)
                && !badUrls.contains(strLink)) {
                badUrls.add(strLink);
            }
        }
        return subUrls;
    }

    public static StringBuilder getResponse(String path, URL url){
        try {
            java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
            uc.setRequestProperty("User-agent", "Mozilla/10.0");

            uc.setRequestProperty("Accept-Charset", "UTF-8"); // encoding
            uc.setReadTimeout(30000);// timeout limit
            uc.connect();// connect
            int status = uc.getResponseCode();

            switch (status) {
                case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504 timeout
                    break;
                case java.net.HttpURLConnection.HTTP_FORBIDDEN://403 forbidden
                    break;
                case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500 server error
                    break;
                case java.net.HttpURLConnection.HTTP_NOT_FOUND://404 not exist
                    break;
                case java.net.HttpURLConnection.HTTP_OK: // ok
                    InputStreamReader reader = new InputStreamReader(uc.getInputStream(), "UTF-8");

                    int ch;
                    StringBuilder sb = new StringBuilder("");
                    while((ch = reader.read())!= -1){
                        sb.append((char)ch);
                    }
                    return sb;
            }

        } catch (java.net.MalformedURLException e) { // invalid address format
            e.printStackTrace();
        } catch (java.io.IOException e) { // connection broken
            e.printStackTrace();
        }
        return new StringBuilder("");
    }
    public Map getResult () {
        return result;
    }
    /**
     * Whether the crawler is stopped
     * @return boolean
     */
    public boolean isStopped () {
        return stopped;
    }
    public static void main (String[] args) {
        SimpleCrawler crawler = new SimpleCrawler();
        // crawl this url
        crawler.Crawl("http://java.sun.com", 2);
        // wait until crawler stopped
        while (!crawler.isStopped()) {
            try{
                Thread.sleep(10000);
            } catch (Exception e) {
                continue;
            }
        }
        // show the results
        Map result = crawler.getResult();
        System.out.println(result.size());
        for (Object key : result.keySet()) {
            System.out.println(key.toString());
            if (result.get(key).toString().length() > 50)
                System.out.println(result.get(key).toString().substring(0, 50));
            else
                System.out.println(result.get(key));
        }
    }
}

The Result



Download
The program is available at github
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Net/src/test/SimpleCrawler.java

Reference
http://java.sun.com/developer/technicalArticles/ThirdParty/WebCrawler/

Tuesday, February 14, 2012

Java Practice: java.net practice, Use Google Geocode Web Service

Just simple log:

Assume we have the java application below:

package test;

import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class GeocodeService {
    public static void main (String args[]) {
        String result = null;
        try {
            System.out.println("First request\n\n");
            // request service by Lat, Lng
            StringBuilder sb = getResponse("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.70594140,-74.0088760&sensor=true&language=ja");
            result = sb.toString();
            System.out.println(result+"\n");
            System.out.println("Second request\n\n");
            sb.setLength(0);
            // request service by address
            sb = getResponse("http://maps.googleapis.com/maps/api/geocode/json?address="
                    +java.net.URLEncoder.encode("59 ウォール街 マンハッタン ニューヨーク 10005 アメリカ合衆国", "UTF-8")+"&sensor=true&language=en");
            result = sb.toString();
            System.out.println(result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static StringBuilder getResponse(String path){
        try {
            System.out.println(path);
            java.net.URL url = new java.net.URL(path);
            java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
            uc.setRequestProperty("User-agent", "Mozilla/5.0");

            uc.setRequestProperty("Accept-Charset", "UTF-8"); // encoding
            uc.setReadTimeout(30000);// timeout limit
            uc.connect();// connect
            int status = uc.getResponseCode();

            switch (status) {
                case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504 timeout
                    break;
                case java.net.HttpURLConnection.HTTP_FORBIDDEN://403 forbidden
                    break;
                case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500 server error
                    break;
                case java.net.HttpURLConnection.HTTP_NOT_FOUND://404 not exist
                    break;
                case java.net.HttpURLConnection.HTTP_OK: // ok
                    InputStreamReader reader = new InputStreamReader(uc.getInputStream(), "UTF-8");

                    int ch;
                    StringBuilder sb = new StringBuilder("");
                    while((ch = reader.read())!= -1){
                        sb.append((char)ch);
                    }
                    return sb;
            }

        } catch (java.net.MalformedURLException e) { // invalid address format
            e.printStackTrace();
        } catch (java.io.IOException e) { // connection broken
            e.printStackTrace();
        }
        return null;
    }
}

The result will be:

First request


http://maps.googleapis.com/maps/api/geocode/json?latlng=40.70594140,-74.0088760&sensor=true&language=ja
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "2",
               "short_name" : "2",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "ハノーバー・ストリート",
               "short_name" : "ハノーバー・ストリート",
               "types" : [ "route" ]
            },
            {
               "long_name" : "ダウンタウン",
               "short_name" : "ダウンタウン",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "10005",
               "short_name" : "10005",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "2 ハノーバー・ストリート マンハッタン ニューヨーク 10005 アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.70595330,
                  "lng" : -74.00886570
               },
               "southwest" : {
                  "lat" : 40.70549480,
                  "lng" : -74.00910170
               }
            },
            "location" : {
               "lat" : 40.70594550,
               "lng" : -74.00888990
            },
            "location_type" : "RANGE_INTERPOLATED",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.70707303029150,
                  "lng" : -74.00763471970851
               },
               "southwest" : {
                  "lat" : 40.70437506970850,
                  "lng" : -74.01033268029151
               }
            }
         },
         "types" : [ "street_address" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Wall St",
               "short_name" : "Wall St",
               "types" : [ "subway_station", "establishment", "transit_station" ]
            },
            {
               "long_name" : "ダウンタウン",
               "short_name" : "ダウンタウン",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "10005",
               "short_name" : "10005",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Wall St, ニューヨーク 10005 アメリカ合衆国",
         "geometry" : {
            "location" : {
               "lat" : 40.7068210,
               "lng" : -74.00910
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.70816998029150,
                  "lng" : -74.00775101970849
               },
               "southwest" : {
                  "lat" : 40.70547201970850,
                  "lng" : -74.01044898029151
               }
            }
         },
         "types" : [ "subway_station", "establishment", "transit_station" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "10265",
               "short_name" : "10265",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "ダウンタウン",
               "short_name" : "ダウンタウン",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "マンハッタン ニューヨーク 10265 アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.70839880,
                  "lng" : -74.00650899999999
               },
               "southwest" : {
                  "lat" : 40.70530210,
                  "lng" : -74.01091610
               }
            },
            "location" : {
               "lat" : 40.70556480,
               "lng" : -74.0081070
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.70839880,
                  "lng" : -74.00650899999999
               },
               "southwest" : {
                  "lat" : 40.70530210,
                  "lng" : -74.01091610
               }
            }
         },
         "types" : [ "postal_code" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "10005",
               "short_name" : "10005",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "ウォール・ストリート",
               "short_name" : "ウォール・ストリート",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "WALL STREET",
               "short_name" : "WALL STREET",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "WALL STREET ニューヨーク 10005 アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.7091540,
                  "lng" : -73.99918690
               },
               "southwest" : {
                  "lat" : 40.6949950,
                  "lng" : -74.0135830
               }
            },
            "location" : {
               "lat" : 40.69984330,
               "lng" : -74.00724360
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.7091540,
                  "lng" : -73.99918690
               },
               "southwest" : {
                  "lat" : 40.6949950,
                  "lng" : -74.0135830
               }
            }
         },
         "types" : [ "postal_code" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "ダウンタウン",
               "short_name" : "ダウンタウン",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "ダウンタウン ニューヨーク アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.74252620,
                  "lng" : -73.97164459999999
               },
               "southwest" : {
                  "lat" : 40.70046310,
                  "lng" : -74.01933500000001
               }
            },
            "location" : {
               "lat" : 40.72300840,
               "lng" : -74.00063279999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.74252620,
                  "lng" : -73.97164459999999
               },
               "southwest" : {
                  "lat" : 40.70046310,
                  "lng" : -74.01933500000001
               }
            }
         },
         "types" : [ "neighborhood", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "マンハッタン",
               "short_name" : "マンハッタン",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "マンハッタン ニューヨーク アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.8822140,
                  "lng" : -73.9070
               },
               "southwest" : {
                  "lat" : 40.67954790,
                  "lng" : -74.0472850
               }
            },
            "location" : {
               "lat" : 40.78343450,
               "lng" : -73.96624950
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.8200450,
                  "lng" : -73.90331300000001
               },
               "southwest" : {
                  "lat" : 40.6980780,
                  "lng" : -74.03514899999999
               }
            }
         },
         "types" : [ "sublocality", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "ニューヨーク アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.8822140,
                  "lng" : -73.9070
               },
               "southwest" : {
                  "lat" : 40.67954790,
                  "lng" : -74.0472850
               }
            },
            "location" : {
               "lat" : 40.78306030,
               "lng" : -73.97124880
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.8822140,
                  "lng" : -73.9070
               },
               "southwest" : {
                  "lat" : 40.67954790,
                  "lng" : -74.0472850
               }
            }
         },
         "types" : [ "administrative_area_level_2", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "ニューヨーク",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "ニューヨーク アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.9175770,
                  "lng" : -73.7002720
               },
               "southwest" : {
                  "lat" : 40.4959080,
                  "lng" : -74.25908790
               }
            },
            "location" : {
               "lat" : 40.71435280,
               "lng" : -74.00597309999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.9175770,
                  "lng" : -73.7002720
               },
               "southwest" : {
                  "lat" : 40.4959080,
                  "lng" : -74.25908790
               }
            }
         },
         "types" : [ "locality", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "ニューヨーク",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "ニューヨーク アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 45.0158650,
                  "lng" : -71.85626990
               },
               "southwest" : {
                  "lat" : 40.49594540,
                  "lng" : -79.76214390
               }
            },
            "location" : {
               "lat" : 43.29942850,
               "lng" : -74.21793260000001
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 45.0158650,
                  "lng" : -71.85626990
               },
               "southwest" : {
                  "lat" : 40.49594540,
                  "lng" : -79.76214390
               }
            }
         },
         "types" : [ "administrative_area_level_1", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "アメリカ合衆国",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "アメリカ合衆国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 71.3898880,
                  "lng" : -66.94539480000002
               },
               "southwest" : {
                  "lat" : 18.91106430,
                  "lng" : 172.45469670
               }
            },
            "location" : {
               "lat" : 37.090240,
               "lng" : -95.7128910
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 71.3898880,
                  "lng" : -66.94539480000002
               },
               "southwest" : {
                  "lat" : 18.91106430,
                  "lng" : 172.45469670
               }
            }
         },
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}


Second request


http://maps.googleapis.com/maps/api/geocode/json?address=59+%E3%82%A6%E3%82%A9%E3%83%BC%E3%83%AB%E8%A1%97+%E3%83%9E%E3%83%B3%E3%83%8F%E3%83%83%E3%82%BF%E3%83%B3+%E3%83%8B%E3%83%A5%E3%83%BC%E3%83%A8%E3%83%BC%E3%82%AF+10005+%E3%82%A2%E3%83%A1%E3%83%AA%E3%82%AB%E5%90%88%E8%A1%86%E5%9B%BD&sensor=true&language=en
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "59",
               "short_name" : "59",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Wall St",
               "short_name" : "Wall St",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Lower Manhattan",
               "short_name" : "Lower Manhattan",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Manhattan",
               "short_name" : "Manhattan",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "New York",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "New York",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "10005",
               "short_name" : "10005",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "59 Wall St, New York, NY 10005, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.70593059999999,
                  "lng" : -74.00882020
               },
               "southwest" : {
                  "lat" : 40.70591870,
                  "lng" : -74.00883060
               }
            },
            "location" : {
               "lat" : 40.70591870,
               "lng" : -74.00883060
            },
            "location_type" : "RANGE_INTERPOLATED",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.70727363029150,
                  "lng" : -74.00747641970850
               },
               "southwest" : {
                  "lat" : 40.70457566970850,
                  "lng" : -74.01017438029150
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

Download:
The file GeocodeService.java at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/Net/src/test

Reference:
http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
http://code.google.com/intl/en/apis/maps/documentation/geocoding/