google_application_credentials google bigquery oauth google-api

oauth - bigquery - ¿Qué API de Google usar para obtener el nombre, apellido, imagen, etc. del usuario?



google_application_credentials export (7)

Tengo la autorización auth con google funcionando correctamente y estoy obteniendo datos de la api de contactos. Ahora, deseo obtener el nombre, el apellido y la imagen de un usuario de Gmail mediante programación. ¿Qué google api puedo usar para obtener estos datos?


Encontré la respuesta mientras miraba a mi alrededor en el foro de la API de contactos. Cuando obtenga el feed de resultados, solo haga lo siguiente en Java-

String Name = resultFeed.getAuthors().get(0).getName(); String emailId = resultFeed.getId();

Todavía estoy buscando una manera de obtener la imagen de perfil de usuario.


La API de contactos quizás funcione, pero debe solicitar permiso al usuario para acceder a todos los contactos. Si fuera un usuario, eso me haría desconfiar de otorgar el permiso (porque esto esencialmente le otorga permiso para enviar spam a todos mis contactos ...)

Encontré que la respuesta aquí es útil, y solo solicita "información básica de perfil":

Obtener información de usuario a través de la API de Google

He utilizado este enfoque con éxito y puedo confirmar que devuelve el siguiente objeto Json:

{ "id": "..." "email": "...", "verified_email": true, "name": "....", "given_name": "...", "family_name": "...", "link": "...", "picture": "...", "gender": "male", "locale": "en" }


La forma más sencilla de obtener esta información sería desde la API de Google +. Específicamente el

https://developers.google.com/+/api/latest/people/get

Cuando use la API use el siguiente HTTP GET:

GET https://www.googleapis.com/plus/v1/people/me

Esto devolverá toda la información anterior solicitada por el usuario.




Utilice este Código para acceder a la credencial de inicio de sesión de Google Gmail oAuth2:

Nombre de la clase: OAuthHelper

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map.Entry; import java.util.SortedSet; import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import oauth.signpost.commonshttp.HttpRequestAdapter; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; import oauth.signpost.signature.HmacSha1MessageSigner; import oauth.signpost.signature.OAuthMessageSigner; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.util.Log; public class OAuthHelper { private static final String TAG = "OAuthHelper"; private OAuthConsumer mConsumer; private OAuthProvider mProvider; private String mCallbackUrl; public OAuthHelper(String consumerKey, String consumerSecret, String scope, String callbackUrl) throws UnsupportedEncodingException { mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); mProvider = new CommonsHttpOAuthProvider("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + URLEncoder.encode(scope, "utf-8"), "https://www.google.com/accounts/OAuthGetAccessToken", "https://www.google.com/accounts/OAuthAuthorizeToken?hd=default"); mProvider.setOAuth10a(true); mCallbackUrl = (callbackUrl == null ? OAuth.OUT_OF_BAND : callbackUrl); } public String getRequestToken() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { String authUrl = mProvider.retrieveRequestToken(mConsumer, mCallbackUrl); System.out.println("Gautam AUTH URL : " + authUrl); return authUrl; } public String[] getAccessToken(String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { mProvider.retrieveAccessToken(mConsumer, verifier); return new String[] { mConsumer.getToken(), mConsumer.getTokenSecret() }; } public String[] getToken() { return new String[] { mConsumer.getToken(), mConsumer.getTokenSecret() }; } public void setToken(String token, String secret) { mConsumer.setTokenWithSecret(token, secret); } public String getUrlContent(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { HttpGet request = new HttpGet(url); // sign the request mConsumer.sign(request); // send the request HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); // get content BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); System.out.println("gautam INFO : " + sb.toString()); return sb.toString(); } public String getUserProfile(String t0, String t1, String url) { try { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(t0, t1); HttpGet request = new HttpGet(url); // sign the request consumer.sign(request); // send the request HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; //String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line ); in.close(); System.out.println("Gautam Profile : " + sb.toString()); return sb.toString(); } catch (Exception e) { System.out.println("Error in Geting profile Info : " + e); return ""; } } public String buildXOAuth(String email) { String url = String.format("https://mail.google.com/mail/b/%s/smtp/", email); HttpRequestAdapter request = new HttpRequestAdapter(new HttpGet(url)); // Sign the request, the consumer will add any missing parameters try { mConsumer.sign(request); } catch (OAuthMessageSignerException e) { Log.e(TAG, "failed to sign xoauth http request " + e); return null; } catch (OAuthExpectationFailedException e) { Log.e(TAG, "failed to sign xoauth http request " + e); return null; } catch (OAuthCommunicationException e) { Log.e(TAG, "failed to sign xoauth http request " + e); return null; } HttpParameters params = mConsumer.getRequestParameters(); // Since signpost doesn''t put the signature into params, // we''ve got to create it again. OAuthMessageSigner signer = new HmacSha1MessageSigner(); signer.setConsumerSecret(mConsumer.getConsumerSecret()); signer.setTokenSecret(mConsumer.getTokenSecret()); String signature; try { signature = signer.sign(request, params); } catch (OAuthMessageSignerException e) { Log.e(TAG, "invalid oauth request or parameters " + e); return null; } params.put(OAuth.OAUTH_SIGNATURE, OAuth.percentEncode(signature)); StringBuilder sb = new StringBuilder(); sb.append("GET "); sb.append(url); sb.append(" "); int i = 0; for (Entry<String, SortedSet<String>> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue().first(); int size = entry.getValue().size(); if (size != 1) Log.d(TAG, "warning: " + key + " has " + size + " values"); if (i++ != 0) sb.append(","); sb.append(key); sb.append("=/""); sb.append(value); sb.append("/""); } Log.d(TAG, "xoauth encoding " + sb); Base64 base64 = new Base64(); try { byte[] buf = base64.encode(sb.toString().getBytes("utf-8")); return new String(buf, "utf-8"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "invalid string " + sb); } return null; } }

// ===================================

Crear: WebViewActivity.class

import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.Window; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActivity extends Activity { //WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); setContentView(webview); // Load the page Intent intent = getIntent(); if (intent.getData() != null) { webview.loadUrl(intent.getDataString()); } webview.setWebChromeClient(new WebChromeClient() { // Show loading progress in activity''s title bar. @Override public void onProgressChanged(WebView view, int progress) { setProgress(progress * 100); } }); webview.setWebViewClient(new WebViewClient() { // When start to load page, show url in activity''s title bar @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { setTitle(url); if (url.startsWith("my-activity")) { Intent result = new Intent(); System.out.println("Gautam my-activity : " + url); result.putExtra("myurl", url); setResult(RESULT_OK, result); finish(); } } @Override public void onPageFinished(WebView view, String url) { System.out.println("Gautam Page Finish..."); CookieSyncManager.getInstance().sync(); // Get the cookie from cookie jar. String cookie = CookieManager.getInstance().getCookie(url); System.out.println("Gautam Cookie : " + cookie); if (cookie == null) { return; } // Cookie is a string like NAME=VALUE [; NAME=VALUE] String[] pairs = cookie.split(";"); for (int i = 0; i < pairs.length; ++i) { String[] parts = pairs[i].split("=", 2); // If token is found, return it to the calling activity. System.out.println("Gautam=> "+ parts[0] + " = " + parts[1]); if (parts.length == 2 && parts[0].equalsIgnoreCase("oauth_token")) { Intent result = new Intent(); System.out.println("Gautam AUTH : " + parts[1]); result.putExtra("token", parts[1]); setResult(RESULT_OK, result); finish(); } } } }); } }

// =========================

Llamar desde: MainActivity.class

import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.http.HttpResponse; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener{ Button btnLogin; OAuthHelper MyOuthHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnLogin = (Button)findViewById(R.id.btnLogin); btnLogin.setOnClickListener(this); } @Override protected void onResume() { /*System.out.println("On Resume call "); try { String[] token = getVerifier(); if (token != null){ String accessToken[] = MyOuthHelper.getAccessToken(token[1]); } } catch (Exception e) { System.out.println("gautam error on Resume : " + e); }*/ super.onResume(); } private String[] getVerifier(String url) { // extract the token if it exists Uri uri = Uri.parse(url); if (uri == null) { return null; } String token = uri.getQueryParameter("oauth_token"); String verifier = uri.getQueryParameter("oauth_verifier"); return new String[] { token, verifier }; } @Override public void onClick(View v) { try { MyOuthHelper = new OAuthHelper("YOUR CLIENT ID", "YOUR SECRET KEY", "https://www.googleapis.com/auth/userinfo.profile", "my-activity://localhost"); } catch (Exception e) { System.out.println("gautam errorin Class call : " + e); } try { String uri = MyOuthHelper.getRequestToken(); Intent intent = new Intent(MainActivity.this, WebViewActivity.class); intent.setData(Uri.parse(uri)); startActivityForResult(intent, 0); /* startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));*/ } catch (Exception e) { System.out.println("Gautm Error in getRequestTokan : " + e); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 0: if (resultCode != RESULT_OK || data == null) { return; } // Get the token. String url = data.getStringExtra("myurl"); try { String[] token = getVerifier(url); if (token != null){ String accessToken[] = MyOuthHelper.getAccessToken(token[1]); System.out.println("Gautam Final [0] : " + accessToken[0] + " , [1] : " + accessToken[1]); //https://www.googleapis.com/oauth2/v1/userinfo?alt=json // String myProfile = MyOuthHelper.getUserProfile(accessToken[0], accessToken[1], "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); String myProfile = MyOuthHelper.getUrlContent("https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); } } catch (Exception e) { System.out.println("gautam error on Resume : " + e); } return; } super.onActivityResult(requestCode, resultCode, data); } }

// =================================

Y finalmente, la información de su perfil viene, solo mire en la impresión de su mensaje Logcat.

Nota: No se olvidó de poner el permiso de Internet en el archivo de manifiesto

Y su aplicación Regístrese en la consola de Google para el ID de cliente y la clave secreta para el registro de la aplicación. Por favor, consulte este paso: Paso de registro de la aplicación


use este código obtener el primer nombre y el apellido de un usuario de Google

final HttpTransport transport = new NetHttpTransport(); final JsonFactory jsonFactory = new JacksonFactory(); GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) .setAudience(Arrays.asList(clientId)) .setIssuer("https://accounts.google.com") .build(); GoogleIdToken idToken = null; try { idToken = verifier.verify(googleAuthenticationPostResponse.getId_token()); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } GoogleIdToken.Payload payload = null; if (idToken != null) { payload = idToken.getPayload(); } String firstName = payload.get("given_name").toString(); String lastName = payload.get("family_name").toString();