title: Authenticate programmatically to Google with OAuth2
body: <p>How can I authenticate programmatically to Google?
  Now that ClientLogin (<a href="https://developers.google.com/accounts/docs/AuthForInstalledApps" rel="noreferrer">https://developers.google.com/accounts/docs/AuthForInstalledApps</a>)
  is deprecated, how can we perform a programmatic authentication to Google with OAuth2?</p>
  
  <p>With ClientLogin we could perform a post to
  <a href="https://www.google.com/accounts/ClientLogin" rel="noreferrer">https://www.google.com/accounts/ClientLogin</a>
  with email and password parameters and obtain the authentication token.</p>
  
  <p>With OAuth2 i can't find a solution!</p>
  
  #
  
  <p>My app is a java background process.
  I saw, following this link: developers.google.com/accounts/docs/OAuth2InstalledApp#refresh, how to obtain a new access token using a refreshed token.</p>
  
  <p>The problem is that I can't find a java example about how to instantiate an Analytics object (for example) to perform a query when I have a new valid access token</p>
  
  <p>This is my code that returns a 401 Invalid credentials when invoke the "execute()":</p>
  
  <pre><code>public class Test {
  
  static final String client_id = "MY_CLIENT_ID";
  static final String client_secret = "MY_SECRET";
  static final String appName = "MY_APP";
  
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  
  static String access_token = "xxxx";
  static String refreshToken = "yyyyy";
  
  public static void main (String args[]){
  
      try {
  
          GoogleCredential credential = 
              new GoogleCredential.Builder()
                  .setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setClientSecrets(client_id, client_secret).build();
          credential.setAccessToken(access_token);
          credential.setRefreshToken(refreshToken);
          //GoogleCredential
          Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
              .setApplicationName(appName)
              .setHttpRequestInitializer(credential)
              .build();
  
          Accounts accounts = analytics.management().accounts().list().execute();
      } catch (Exception e) {
          e.printStackTrace();
      } 
  }
  </code></pre>
  
  <p>What is the problem?</p>