There were 2 issues.
First is to always renew the code that you get from https://developers.google.com/oauthplayground/ as we can only use that code once and after that it will always give 400 BAD REQUEST
Second is about RestTemplate. RestTemplate default can not handle gzip which is sent by google. so we need to use Apache HttpClient v4.
Like this:
HttpClient httpClient = HttpClients.createDefault();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Import statements should be like :
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
and dependency should be:
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>