我有oauth授權谷歌正常工作,並從聯繫人API獲取數據。現在,我想以編程方式獲取gmail用戶的名字,姓氏和圖片。我可以使用哪種Google API來獲取這些數據?哪個Google API用於獲取用戶的名字,姓氏,圖片等?
回答
我在聯繫人API論壇中找到了答案。當你得到的結果,飼料,只是做在Java的
String Name = resultFeed.getAuthors().get(0).getName();
String emailId = resultFeed.getId();
下面我仍然在尋找一種方式來獲得用戶的個人資料圖片。
你可以發佈一些代碼示例獲取名字,姓氏,谷歌的電子郵件。您正在請求的網址。我在android應用程序中做同樣的事情。提前致謝。 – Panache 2011-08-31 07:21:41
Java與Google API有什麼關係? – 2013-03-22 06:11:11
對於圖片,您可以使用谷歌聯繫人數據API太:看http://code.google.com/intl/fr/apis/contacts/docs/3.0/developers_guide_protocol.html#retrieving_photo
但是如何爲登錄用戶檢索照片?我試過的https://www.google.com/m8/feeds/photos/media/default/[email protected] =的access_token ...但我得到的錯誤「照片查詢失敗 - 無效的聯繫ID」? – 2011-08-10 23:17:27
在您的網址中,只需輸入URL編碼的電子郵件地址(寫入%40而不是@)即可運行... – olivierlemasle 2011-08-11 20:54:34
我剛剛發現了一個新的Google API,您可以使用它:便攜式聯繫人API(http:// code。 google.com/intl/fr-FR/apis/contacts/docs/poco/1.0/developers_guide.html)它更容易獲取用戶的照片:你與範圍https://www-opensocial.googleusercontent.com/api認證/ people /,您可以通過請求獲取用戶信息https://www-opensocial.googleusercontent.com/api/people/@me/@self,它包含照片的網址... – olivierlemasle 2011-08-11 20:57:54
觸點API或許有效,但你必須向用戶請求訪問所有聯繫人。如果我是一個用戶,這會讓我警惕批准許可(因爲這基本上允許您發送所有我的聯繫人的垃圾郵件......)
我發現此處的回覆很有用,只要求「基本配置文件信息「:
我已經成功地使用這種方法,並且可以確認返回以下JSON對象:
{
"id": "..."
"email": "...",
"verified_email": true,
"name": "....",
"given_name": "...",
"family_name": "...",
"link": "...",
"picture": "...",
"gender": "male",
"locale": "en"
}
對於這個答案+1,因爲它實際上解決了問題提出的Google API,而不是當前接受的答案,這只是一些隨機的Java代碼。 – 2013-03-22 06:09:12
得到這個信息是從谷歌的最簡單方法+ API。特別是
https://developers.google.com/+/api/latest/people/get
當使用API使用下面的HTTP GET:
GET https://www.googleapis.com/plus/v1/people/me
這將返回所有的從用戶請求的上述信息。
使用此代碼的訪問谷歌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消息打印。
注:並非忘了上網權限清單文件
而且您的應用註冊在谷歌控制檯客戶端ID與密鑰 爲App註冊請尋找此步驟:App Registration Step
如果你使用谷歌的的JavaScript API,你可以驗證,以獲取用戶的個人資料後,使用新的「auth2」 API,包含:
- 名
- 電子郵件
- 圖像URL
使用此代碼得到一個谷歌用戶
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. 獲取在Android中使用Google SignIn API的用戶的名字和姓氏
- 2. 從twitter獲取用戶名和姓氏
- 3. OpsHub - 用戶映射 - 名字姓氏vs(Azure)姓氏,名字
- 4. 僅提取姓氏名字,姓氏
- 5. 查詢用戶的名字,姓氏,圖片,並加入評論
- 6. iOS - 使用Google SignIn SDK獲取名字和姓氏
- 7. 如何獲取登錄的Windows用戶的名字和姓氏?
- 8. 添加用戶的姓氏和名字
- 9. 發現用戶的名字和姓氏?
- 10. WordPress的獲取名字和姓氏
- 11. 用名字和姓氏查找姓名
- 12. 名字和姓氏中的Split姓氏
- 13. 提取名字和姓氏
- 14. 更改姓氏,名字到姓氏,FirstInitial
- 15. 哪個Google API用於獲取用戶擁有的站點
- 16. 使用OAuth從Twitter獲取名字/姓氏/電子郵件
- 17. :姓名,姓氏:姓名
- 18. 從姓氏和姓氏字段中獲取最短的唯一名稱
- 19. 如何從姓名全名的字符串中獲取名字和姓氏
- 20. 單名文本框中的名字和姓氏的姓氏
- 21. Twitter搜索Api獲取用戶名和用戶真實姓名
- 22. Android:如何在成功登錄後獲取Google帳戶用戶名,名字和姓氏
- 23. 如何使用Laravel Socialite從Facebook獲取名字和姓氏?
- 24. 將單個字段分隔成名稱,姓氏和姓氏
- 25. 如何在Django中獲取登錄用戶的名字和姓氏?
- 26. 使用Google People API獲取用戶Google Plus封面圖片
- 27. PowerShell - AD用戶的名字和姓氏的返回值
- 28. 從名字和姓氏生成唯一的用戶名?
- 29. 顯示登錄用戶的全名(名字,姓氏)
- 30. 如何在Excel中創建姓氏,姓氏的帳戶名稱
沒有人的firstName和lastName有任何線索這個?我很驚訝自己,當我沒有找到對谷歌的網站上的任何簡單的答案... – Pranav 2010-01-21 14:35:03
是OAuth的一樣的OpenID? – anon 2010-01-22 03:53:10
您是否想要獲取聯繫人或您認證的用戶的名稱和圖片? – 2010-01-22 04:17:03