【问题标题】:Which Google api to use for getting user's first name, last name, picture, etc?使用哪个 Google api 来获取用户的名字、姓氏、图片等?
【发布时间】:2011-01-07 16:32:27
【问题描述】:

我的 oauth 授权与 google 正常工作,并且正在从联系人 api 获取数据。现在,我想以编程方式获取 gmail 用户的名字、姓氏和图片。我可以使用哪个 google api 来获取这些数据?

【问题讨论】:

  • 没人知道这件事吗?当我在谷歌的网站上没有找到任何简单的答案时,我自己都感到惊讶......
  • 您是要获取联系人的姓名和图片,还是您已通过身份验证的用户?
  • 为用户。获取联系人信息不会很困难,因为它有一个 api。

标签: oauth google-api


【解决方案1】:

我在联系人 API 论坛中环顾四周时找到了答案。当您获得结果提要时,只需在 Java 中执行以下操作-

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

String emailId = resultFeed.getId();

我仍在寻找获取用户个人资料图片的方法。

【讨论】:

  • 您能否发布一些代码示例以获取来自 google 的名字、姓氏、电子邮件。您请求的网址。我在 android 应用程序中做同样的事情。提前致谢。
  • Java 与 Google API 有什么关系?
【解决方案2】:

对于图片,您也可以使用 Google 联系人数据 API:请参阅 http://code.google.com/intl/fr/apis/contacts/docs/3.0/developers_guide_protocol.html#retrieving_photo

【讨论】:

【解决方案3】:

联系人 API 可能有效,但您必须请求用户的许可才能访问所有联系人。如果我是用户,那会让我对授予该权限持谨慎态度(因为这实际上允许您向我的所有联系人发送垃圾邮件......)

我发现这里的回复很有用,并且只要求提供“基本个人资料”:

Get user info via Google API

我已经成功使用了这个方法,可以确认返回如下Json对象:

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

【讨论】:

  • +1 这个答案,因为它实际上解决了问题提出的 Google API,而不是当前接受的答案,它只是一些随机的 Java 代码。
【解决方案4】:

获取此信息的最简单方法是通过 Google + API。特别是

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

使用 api 时使用以下 HTTP GET:

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

这将返回用户请求的所有上述信息。

【讨论】:

【解决方案5】:

使用此代码访问 Google Gmail 登录凭据 oAuth2:

类名: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;
}

}

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

创建: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();
                }
           }
         }



    });


}
}

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

调用来源: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);
 }





 }

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

最后你的个人资料信息来了,看看你的 Logcat 消息打印。

注意:不要忘记将 Internet 权限放入清单文件中

您的应用在 Google 控制台中注册以获取客户端 ID 和密钥 应用注册请看此步骤:App Registration Step

【讨论】:

    【解决方案6】:

    如果您使用的是 google javascript API,您可以在验证后使用新的“auth2”API 来获取用户的个人资料,其中包含:

    • 姓名
    • 电子邮件
    • 图片网址

    https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile

    【讨论】:

      【解决方案7】:

      使用此代码获取 google 用户的 firstNamelastName

      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();
      

      【讨论】:

        猜你喜欢
        • 2021-01-16
        • 2016-08-26
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多