title: How to get access token using gmail api
body: <p>I got the authorization code following <a href="https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse">this document</a>. But when I tried to get access token, I always got errors. Can anyone help me ?</p>
  
  <pre><code>public String AccessToken()
  {
      String accessToken = "";
      StringBuilder strBuild = new StringBuilder();
  
      String authURL = "https://accounts.google.com/o/oauth2/token?";
      String code = "4/SVisuz_x*********************";
      String client_id = "******************e.apps.googleusercontent.com";
      String client_secret = "*******************";
      String redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
      String grant_type="authorization_code";
      strBuild.append("code=").append(code)
              .append("&amp;client_id=").append(client_id)
              .append("&amp;client_secret=").append(client_secret)
              .append("&amp;redirect_uri=").append(redirect_uri)
              .append("&amp;grant_type=").append(grant_type);
      System.out.println(strBuild.toString());
      try{
          URL obj = new URL(authURL);
          HttpURLConnection con = (HttpURLConnection) obj.openConnection();
          con.setDoOutput(true);
          con.setRequestMethod("POST");
  
          con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          con.setRequestProperty("Host", "www.googleapis.com");
  
          //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
          //bw.write(strBuild.toString());
          //bw.close();
  
          DataOutputStream wr = new DataOutputStream(con.getOutputStream());
          wr.writeBytes(strBuild.toString());
          wr.flush();
          wr.close();
  
          //OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
          System.out.println(con.getResponseCode());
          System.out.println(con.getResponseMessage());             
  
      } catch (Exception e)
      {
          System.out.println("Error.");
      }
      return "";
  }
  </code></pre>
  
  <p>when I ran this code, the output is: 
  <code>400
  Bad Request</code></p>