2010-01-21 9 views
14

Mam autoryzację oauth z poprawnym działaniem Google i otrzymuję dane z api kontaktów. Teraz chcę programowo uzyskać imię, nazwisko i zdjęcie użytkownika Gmaila. Którego google api mogę użyć, aby uzyskać te dane?Które api Google użyć, aby uzyskać imię, nazwisko, zdjęcie itp. Użytkownika?

+6

Nikt nie ma pojęcia o tym, to? Byłem zaskoczony, gdy nie znalazłem żadnej prostej odpowiedzi na stronie google ... – Pranav

+0

Czy oauth jest taki sam jak openid? – anon

+0

Czy próbujesz uzyskać nazwę i zdjęcie kontaktów lub uwierzytelnionego użytkownika? –

Odpowiedz

0

Znalazłem odpowiedź, rozglądając się po forum kontaktów. Gdy pojawi się wynik karmić, po prostu wykonaj następujące czynności w Java-

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

String emailId = resultFeed.getId(); 

ja wciąż szuka sposobu, aby uzyskać zdjęcie z profilu użytkownika.

+0

można wysłać próbkę kodu, aby uzyskać imię, nazwisko, adres e-mail z google. Adres URL, o który prosisz. Robię to samo w aplikacji na Androida. Z góry dziękuję. – Panache

+1

Co ma Java wspólnego z interfejsami API Google? –

1

Na zdjęciu, można użyć interfejsu API kontaktów dane Google też: patrz http://code.google.com/intl/fr/apis/contacts/docs/3.0/developers_guide_protocol.html#retrieving_photo

+1

, ale w jaki sposób odzyskasz zdjęcie dla zalogowanego użytkownika? Próbowałem https: //www.google.com/m8/feeds/photos/media/default/[email protected]? Access_token = ... ale pojawia się błąd "Zdjęcie nie powiodło się - nieprawidłowy identyfikator kontaktu". –

+0

W swoim adresie URL wystarczy wpisać kod adresu e-mail (wpisz% 40 zamiast @) i powinien zadziałać ... – olivierlemasle

+0

Właśnie odkryłem nowy interfejs API Google, którego możesz użyć: Przenośny interfejs API kontaktów (http: // kod. google.com/intl/fr-FR/apis/contacts/docs/poco/1.0/developers_guide.html) Łatwiej jest odzyskać zdjęcie użytkownika: uwierzytelniasz się w zakresie https://www-opensocial.googleusercontent.com/api/people /, otrzymujesz informacje o użytkowniku z prośbą https://www-opensocial.googleusercontent.com/api/people/@me/@self i zawiera adres URL zdjęcia ... – olivierlemasle

15

Styki API może działa, ale trzeba prosić o pozwolenie od użytkownika, aby uzyskać dostęp do wszystkich kontaktów. Gdybym był użytkownikiem, spowodowałoby to niechęć do udzielania zgody (ponieważ to zasadniczo daje ci pozwolenie na spamowanie wszystkich moich kontaktów ...)

Znalazłem odpowiedź tutaj, aby była przydatna, i prosi tylko o "podstawowe informacje profilu ":

Get user info via Google API

mam powodzeniem stosowane takie podejście, a może potwierdzić zwraca następujący obiekt JSON:

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

+1 dla tej odpowiedzi, ponieważ w rzeczywistości dotyczy interfejsów Google API zadawanych przez to pytanie, w przeciwieństwie do bieżącej, zaakceptowanej odpowiedzi, która jest po prostu przypadkowym kodem Java. –

1

najprostszy sposób, aby uzyskać te informacje byłyby od Google + API. Konkretnie

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

Podczas korzystania użyć API następujące HTTP GET:

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

ten powróci wszystkie powyższe informacje wymagane od użytkownika.

-1

użyć tego kodu na dostęp do Google Gmail logowania poświadczeń OAuth2:

Class Nazwa: 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; 
} 

} 

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

Utwórz: 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(); 
       } 
      } 
     } 



    }); 


} 
} 

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

dzwonić z: 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); 
} 





} 

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

I na koniec informacja o Twoim profilu pojawia się po prostu w Logcat wydruk wiadomości.

Uwaga: Nie pamiętasz umieścić Permission internetowego w pliku manifestu

A swoją aplikację Rejestracja w konsoli Google dla identyfikatora klienta i klucz tajny Dla App Rejestracji Proszę szuka tego kroku: App Registration Step

1

użyć tego kodu uzyskać imię i lastName Google użytkownik

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(); 
Powiązane problemy