Search code examples
javasslgoogle-geocoderhttpsurlconnection

Using HttpsUrlConnection to access Google Geocoding service


I am in the process of building a series of web services in Java which, among other things, will be relying on Google's Geocoding Maps API to convert physical addresses into latitude and longitude points.

Per the documentation, the geocoding service can be accessed by doing a simple GET, e.g. the following URL:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

Here YOUR_API_KEY would be replaced by the actual key corresponding to your app.

Coming to the actual question, I am planning to use HttpsUrlConnection in Java to make the GET call. However, I am confused about which certificate I should be trusting. Is it safe to simply trust all certificates, or should I be installing a Google SSL certificate into my trust store, and only trust that? I read on Stack Overflow about man-in-the-middle attacks, but I don't know if they be a possibility here.


Solution

  • Depends.

    Is the Google SSL certificate signed by a will known Certificate Authority (CA)?

    If so, that SSL certificate should be in the default truststore that ships with Java and you will not need to do anything to trust that certificate.

    If not, then you will need to specifically trust the Google SSL certificate.

    I personally use the InstallCert program to download and install certificates to the default Java Truststore.

    EDIT

    Here is some example code for you:

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class GoogleMapsTest {
    
        public static void main(String[] args) throws Exception {
    
            URL url = new URL("https://maps.google.com/");
    
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
            connection.setRequestMethod("GET");
    
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            while((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            rd.close();
        }
    }
    

    The above code was inspired by, er (mostly) stolen from How to send HTTP request in java? and How to use HttpURLConnection POST data to web server?