Ho l'autorizzazione oauth con google che funziona correttamente e sto recuperando i dati dall'API dei contatti. Ora, desidero ottenere a livello di programmazione il nome, il cognome e l'immagine di un utente di Gmail. Quale google go può usare per ottenere questi dati?Quale API Google utilizzare per ottenere il nome, il cognome, la foto, ecc. Dell'utente?
risposta
Ho trovato la risposta mentre mi guardavo intorno nel forum dell'API dei contatti. Quando si ottiene il risultato-alimentazione, basta fare quanto segue in Java-
String Name = resultFeed.getAuthors().get(0).getName();
String emailId = resultFeed.getId();
Sto ancora cercando un modo per ottenere l'immagine del profilo utente.
puoi pubblicare alcuni esempi di codice per ottenere nome, cognome, email da google. L'URL che stai richiedendo. Sto facendo lo stesso in app Android. Grazie in anticipo. – Panache
Cosa c'entra Java con le API di Google? –
Per l'immagine, è possibile utilizzare l'API di contatti dati anche per Google: vedi http://code.google.com/intl/fr/apis/contacts/docs/3.0/developers_guide_protocol.html#retrieving_photo
ma come si recupera la foto per l'utente che ha effettuato l'accesso? Ho provato https: //www.google.com/m8/feeds/photos/media/default/[email protected]? Access_token = ... ma ottengo l'errore "Query foto fallita - ID contatto non valido". –
Nel tuo URL, basta URLencode l'indirizzo email (scrivi% 40 invece di @) e dovrebbe funzionare ... – olivierlemasle
Ho appena scoperto una nuova API di Google che puoi utilizzare: Portable Contacts API (http: // code. google.com/intl/fr-FR/apis/contacts/docs/poco/1.0/developers_guide.html) È più facile recuperare la foto dell'utente: ti autentichi con l'ambito https://www-opensocial.googleusercontent.com/api/persone /, ottieni informazioni utente con richiesta https://www-opensocial.googleusercontent.com/api/people/@me/@self e contiene l'URL della foto ... – olivierlemasle
L'API dei contatti funziona, forse, ma è necessario richiedere l'autorizzazione da parte dell'utente di accedere a tutti i contatti. Se fossi un utente, questo mi renderebbe cauto nel concedere il permesso (perché questo essenzialmente ti dà il permesso di spammare tutti i miei contatti ...)
Ho trovato la risposta qui per essere utile, e chiede solo "base informazioni sul profilo ":
ho utilizzato con successo questo approccio, e può confermare che restituisce il seguente oggetto JSON:
{
"id": "..."
"email": "...",
"verified_email": true,
"name": "....",
"given_name": "...",
"family_name": "...",
"link": "...",
"picture": "...",
"gender": "male",
"locale": "en"
}
+1 per questa risposta poiché in realtà si rivolge alle API di Google che la domanda ha posto, in contrasto con la risposta corrente accettata che è solo un codice Java casuale. –
il modo più semplice per ottenere queste informazioni sarebbe da Google + API. In particolare il
https://developers.google.com/+/api/latest/people/get
Quando si utilizza l'API utilizzare il seguente HTTP GET:
GET https://www.googleapis.com/plus/v1/people/me
Ciò restituirà tutte le informazioni di cui sopra richiesti da parte dell'utente.
utilizzare questo codice per l'accesso Google Gmail Accesso credenziali OAuth2:
Nome classe: 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;
}
}
// ================ ===================
Crea: 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();
}
}
}
});
}
}
// =========================
chiamata E: 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);
}
}
// ===================
E infine le informazioni sul profilo in arrivo, basta guardare nel logcat messaggio di stampa.
Nota: non dimenticato di mettere il permesso Internet nel file manifesto
e la tua Registrati App in Google Console per l'ID cliente e la chiave segreta Per App Registrazione Si prega di guardando questo passo: App Registration Step
Se si utilizza l'API javascript di google, è possibile utilizzare la nuova API "auth2" dopo l'autenticazione per ottenere il profilo dell'utente, contenente:
- nome
- URL dell'immagine
https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
uso di questo codice ottenere nome e cognome di un utente 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();
- 1. Perché il nome restituisce solo il cognome?
- 2. Come posso ottenere il nome e il cognome come nome completo in una query MYSQL?
- 3. API Google Calendar: come ottenere CalendarEntry per il calendario predefinito?
- 4. Google place Api PlaceDetails Riferimento foto
- 5. "cognome, nome" -> "nome cognome" in stringhe serializzate
- 6. Recupera il nome e il cognome dell'utente attuale di Windows?
- 7. API e foto di Google Plus?
- 8. Ottenere il nome della città e il codice postale da Google Luogo API su Android
- 9. Espressione regolare di Google Apps Script per ottenere il cognome di una persona
- 10. Come posso ottenere il nome e il cognome dell'utente loggato in Windows?
- 11. Nome/Cognome/Email da Twitter utilizzando OAuth
- 12. Array Javascript ordina per cognome, nome
- 13. Mysql Ordina per cognome quando il nome completo per la colonna
- 14. Come aggiornare il timestamp su una foto o aggiungere il fuso orario su Foto Google+?
- 15. Ricerca Google per API immagine?
- 16. API per digitare il nome della città e ottenere un elenco di possibili città?
- 17. Perché utilizzare il nome "op_Addition" per l'operatore "+" anziché il nome "+"?
- 18. Ottenere Google Maps API key
- 19. Poiché le API dell'elenco dati di Google sono state dichiarate obsolete, quale API utilizzare per i siti Google?
- 20. MVC User.Identity.Name con nome e cognome
- 21. Plus.PeopleApi.getCurrentPerson deprecato in Play services 8.4. Come ottenere il nome, il cognome e il sesso dell'utente utilizzando GoogleSignInApi?
- 22. Utilizzare ecc per la crittografia in ios
- 23. Ordina per cognome
- 24. Come ottenere video (non locali) dall'app Google Foto
- 25. Ottenere il nome parametro
- 26. django queryset - ricerca di nome e cognome
- 27. Ricerca nome completo o nome o cognome nel database MySQL con nome e cognome in colonne separate
- 28. Utilizzare una variabile per il nome di un'applicazione
- 29. Come utilizzare Django per ottenere il nome per il server host?
- 30. Django, registrati utente con nome e cognome?
Nessuno ha alcun indizio su Questo? Sono rimasto sorpreso quando non ho trovato nessuna risposta semplice sul sito web di google ... – Pranav
Oauth è uguale a Openid? – anon
Stai cercando di ottenere il nome e l'immagine per i contatti o per l'utente che hai autenticato? –