【问题标题】:How to retrieve Google Contacts in Windows Form application C#?如何在 Windows 窗体应用程序 C# 中检索 Google 联系人?
【发布时间】:2018-08-02 06:01:39
【问题描述】:

我已经在 asp .net c# 中使用 OAuth 2 实现了检索 Google 联系人。但我想为 Windows 窗体实现相同的功能?如何做到这一点?您能指导我从 C# 对 Windows 进行哪些修改吗?和 之后如何注销用户? 我还想在 Gridview 中显示联系人的电子邮件 ID。 提前谢谢你。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Google.GData.Client;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Extensions;
public partial class TutorialCode_GoogleContactAPI_google_contact_api : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["code"] != null)
            GetAccessToken();
    }
    protected void googleButton_Click(object sender, EventArgs e)
    {
        /*https://developers.google.com/accounts/docs/OAuth2InstalledApp
          https://developers.google.com/google-apps/contacts/v3/
          https://developers.google.com/accounts/docs/OAuth2WebServer
          https://developers.google.com/oauthplayground/
        */
        string clientId = "";
        string redirectUrl = "http://localhost:2216/index.aspx";
        Response.Redirect("https://accounts.google.com/o/oauth2/auth?redirect_uri=" + redirectUrl + "&response_type=code&client_id=" + clientId + "&scope=https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline");
    }
    public void GetAccessToken()
    {
        string code = Request.QueryString["code"];
        string google_client_id = "";
        string google_client_sceret = "";
        string google_redirect_url = "http://localhost:2216/index.aspx";

        /*Get Access Token and Refresh Token*/
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
        webRequest.Method = "POST";
        string parameters = "code=" + code + "&client_id=" + google_client_id + "&client_secret=" + google_client_sceret + "&redirect_uri=" + google_redirect_url + "&grant_type=authorization_code";
        byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.ContentLength = byteArray.Length;
        Stream postStream = webRequest.GetRequestStream();
        // Add the post data to the web request
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
        WebResponse response = webRequest.GetResponse();
        postStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(postStream);
        string responseFromServer = reader.ReadToEnd();
        GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
        /*End*/
        GetContacts(serStatus);
    }
    public void GetContacts(GooglePlusAccessToken serStatus)
    {
        string refreshToken = serStatus.refresh_token;
        string accessToken = serStatus.access_token;
        string scopes = "https://www.google.com/m8/feeds/contacts/default/full/";
        OAuth2Parameters oAuthparameters = new OAuth2Parameters()
        {
            RedirectUri = "http://localhost:2216/index.aspx",
            Scope = scopes,
            AccessToken = accessToken,
            RefreshToken = refreshToken
        };


        RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
        ContactsRequest cr = new ContactsRequest(settings);
        ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
        query.NumberToRetrieve = 5000;
        Feed<Contact> feed = cr.Get<Contact>(query);

        StringBuilder sb = new StringBuilder();
        int i = 1;
        foreach (Contact entry in feed.Entries)
        {
            foreach (EMail email in entry.Emails)
            {
                sb.Append(i + "&nbsp;").Append(email.Address).Append("<br/>");
                i++;
            }
        }
        /*End*/
        dataDiv.InnerHtml = sb.ToString();
    }
}

【问题讨论】:

    标签: c# winforms api google-api google-contacts-api


    【解决方案1】:

    希望这会有所帮助。您可以使用 Feed 返回值并在 UI 上绑定/显示。

    using Google.Contacts;
    using Google.GData.Client;
    using Google.GData.Contacts;
    using Google.GData.Extensions;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                GetAccessToken();
    
            }
    
            public void GetAccessToken()
            {
                string code = "";
                string google_client_id = "";
                string google_client_sceret = "";
                string google_redirect_url = "http://localhost:2216/index.aspx";
    
                /*Get Access Token and Refresh Token*/
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
                webRequest.Method = "POST";
                string parameters = "code=" + code + "&client_id=" + google_client_id + "&client_secret=" + google_client_sceret + "&redirect_uri=" + google_redirect_url + "&grant_type=authorization_code";
                byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = byteArray.Length;
                Stream postStream = webRequest.GetRequestStream();
                // Add the post data to the web request
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                WebResponse response = webRequest.GetResponse();
                postStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(postStream);
                string responseFromServer = reader.ReadToEnd();
                GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
                /*End*/
                GetContacts(serStatus);
            }
            public Feed<Contact> GetContacts(GooglePlusAccessToken serStatus)
            {
                string refreshToken = serStatus.refresh_token;
                string accessToken = serStatus.access_token;
                string scopes = "https://www.google.com/m8/feeds/contacts/default/full/";
                OAuth2Parameters oAuthparameters = new OAuth2Parameters()
                {
                    RedirectUri = "http://localhost:2216/index.aspx",
                    Scope = scopes,
                    AccessToken = accessToken,
                    RefreshToken = refreshToken
                };
    
    
                RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
                ContactsRequest cr = new ContactsRequest(settings);
                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.NumberToRetrieve = 5000;
                Feed<Contact> feed = cr.Get<Contact>(query);
    
                return feed;
            }
    
        }
    }
    

    【讨论】:

    • 我收到错误:- 当前上下文中不存在名称“请求”
    • 已更新。我已删除请求。您可以提供静态代码或通过用户输入获取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2015-01-08
    • 2017-03-02
    • 2013-10-26
    相关资源
    最近更新 更多