I believe the reason for the HTTP 400 (Bad Request) is you are sending code
, client_id
, client_secret
, grant_type
, and redirect_uri
as HTTP request headers where you need to be sending them as query parameters in the body of the HTTP POST request (according to the Google OAuth2InstalledApp docs).
Take a look at Using java.net.URLConnection to fire and handle HTTP requests for a good example of how to send the HTTP POST. You'll need to take code
, client_id
, etc. and write them as a query string in the body:
// partial example only: only code and client_id are included
String query = String.format("code=%s&client_id=%s", code, client_id);
OutputStream out = con.getOutputStream();
out.write(query.getBytes("UTF-8"));
From the Google OAuth2 documentation, a sample HTTP POST request might look something like this:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code