Search code examples
androidgoogle-apigoogle-books

Using an android key for google apps


I am writing my first app that uses a google API (google books), and have created an API key for the app fingerprint and package name.

How do I pass the key to the api correctly? I have tried

public BookInfo execute() {
  URL serviceURL;
  try {
    serviceURL = expandVariables("https://www.googleapis.com/books/v1/$METHOD&key=$KEY&country=$COUNTRY");
    HttpURLConnection connection = (HttpURLConnection) serviceURL.openConnection();
    if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
      Log.i("google-books-api", "API rejected call with code " + connection.getResponseCode() + " ");
    }

    // parse the result, and process it
}

Now, this is rejected with code 403 (forbidden), which makes a lot of sense... since it is essentially a plain http call. But how do i pass the additional credentials that allow the API to authenticate the key against the fingerprint and package name.


Solution

  • You need to use setRequestProperty to add the API key into the header of your request.