在Java中获取谷歌的电子邮件/用户名,通常是通过OAuth2.0认证过程来实现的。OAuth2.0是一种授权框架,允许用户在不提供用户名和密码的情况下授权第三方应用访问他们的谷歌账户信息。
以下是使用Google OAuth2.0 API获取用户电子邮件/用户名的步骤:
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class GoogleEmailExample {
private static final String APPLICATION_NAME = "Google Email Example";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final List<String> SCOPES = Collections.singletonList("https://www.googleapis.com/auth/plus.me");
private static final String CREDENTIALS_FILE_PATH = "/path/to/your/credentials.json";
public static void main(String[] args) throws IOException, GeneralSecurityException {
// Load client secrets.
InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(dataStoreFactory)
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
// Build Plus service and get user's email.
Plus plusService = new Plus.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
Person person = plusService.people().get("me").execute();
String email = person.getEmails().get(0).getValue();
System.out.println("User's email: " + email);
}
}
请注意,这个示例使用了Google+ API来获取用户的电子邮件/用户名,但是Google+ API已经被弃用,因此这个示例可能在未来不再有效。您可以考虑使用其他Google API来替代,例如Google People API。
领取专属 10元无门槛券
手把手带您无忧上云