Nov 8, 2018

Java HttpURLConnection example to Get Google OAuth 2.0 Access Token

There are Http Clients from Apache, many RESTFUL implementation such as Jersey. But sometimes you still may just want to use Java to access directly. Here is an example to get access_token from Google.


  String url = "https://accounts.google.com/o/oauth2/token";
  URL obj = new URL(url);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
 
  //add reuqest header
  con.setRequestMethod("POST");
  con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 
  String urlParameters = "code=" + request.getParameter("code") + "&client_id=" + clientId + "&client_secret=" + CLIENT_SECRET + "&redirect_uri=" + redirectURI + "&grant_type=authorization_code";
// for Google OAuth 2.0

 
  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();
 
  int responseCode = con.getResponseCode();
  System.out.println("Response Code : " + responseCode);
 
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
 
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
 
  //print result
  System.out.println(response.toString());