Getting country based on IP I'm using Struts2 and Google App Engine. Below is my program for getting the country based on the IP of the visitor of the website.

In my Struts2 action:

HttpServletRequest request = ServletActionContext.getRequest();
String IP = request.getRemoteAddr();
String countryCode = Utilities.fetchUrl( "http://api.hostip.info/country.php?ip=" + IP );
if ( countryCode != null){
    String country = CountryUtil.COUNTRY_MAP.get( countryCode );
    System.out.println("COUNTRY: " + country);
}


My fetchUrl static function:

public static String fetchUrl(String strUrl){
    String output = "";
    String line = null;
    try {

        URL url = new URL( strUrl );
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((line = reader.readLine()) != null) {
            output += line;
        }
        reader.close();

    } catch (MalformedURLException e) {
        System.out.println("ERROR CATCHED: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("ERROR CATCHED: " + e.getMessage());
        return null;
    }

    return output;
}


My COUNTRY_MAP:

public static final Map&lt;String, String&gt; COUNTRY_MAP;
static {
    Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
    map.put("AF", "afghanistan");
    map.put("AL", "albania");
    ...
    map.put("ZW", "zimbabwe");
    COUNTRY_MAP = Collections.unmodifiableMap( map );
}


Any suggestion on improving its speed?  I also need suggestions for the coding.
The slowest part will be the request to the remote server. There is not much you can do to make this faster. You may want to cache the results you get back from hostip, or you may want to have a local database.

Furthermore, the API seems to return XX if it does not know the country, you may want to check for that.

Also, you do not close the InputStream or the InputStreamReader, and it is possible that you do not close the BufferedReader when an exception occurs. I don't know exactly whether this will cause any problems.