csharp Google与restsharp和google api联系。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Google与restsharp和google api联系。相关的知识,希望对你有一定的参考价值。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Test.Helper;

namespace Test.Controllers
{
    public class GoogleController : Controller
    {
        private TestEntity db = new TestEntity();

        private string clientId = ConfigurationManager.AppSettings["GoogleClientId"];
        private string clientSecret = ConfigurationManager.AppSettings["GoogleSecretKey"];
        private string returnUri = ConfigurationManager.AppSettings["GoogleReturnUri"];

        // GET: Google
        public ActionResult Index()
        {
            var clientAuth = new RestClient();
            clientAuth.BaseUrl = "https://accounts.google.com/o/oauth2/auth";

            var request = new RestRequest(Method.GET);
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("scope", "https://www.google.com/m8/feeds/");
            request.AddParameter("redirect_uri", returnUri);
            request.AddParameter("response_type", "code");
            request.AddParameter("client_id", clientId);
            request.AddParameter("approval_prompt", "force");

            var response = clientAuth.Execute(request);
            Response.Redirect(response.ResponseUri.ToString());

            return View();
        }

        public async Task<ActionResult> GetContacts()
        {
            List<Contacts> contactlist = new List<Contacts>();

            var code = Request.QueryString["code"];

            if (code != null)
            {
                var client = new RestClient();
                client.BaseUrl = "https://accounts.google.com/o/oauth2/token";
                var request = new RestRequest(Method.POST);

                request.AddParameter("code", code);
                request.AddParameter("redirect_uri", returnUri);
                request.AddParameter("client_id", clientId);
                request.AddParameter("scope", "https://www.google.com/m8/feeds/");
                request.AddParameter("client_secret", clientSecret);
                request.AddParameter("grant_type", "authorization_code");

                // most important part !!!! --------------------------
                //.ContentType = "application/x-www-urlencoded";

                var response = client.Execute(request);
                response.ContentType = "application/x-www-urlencoded";

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var content = JsonConvert.DeserializeObject<Token>(response.Content);

                    var access_token = content.access_token;
                    var token_type = content.token_type;
                    var expires_in = content.expires_in;
                    var refresh_token = content.refresh_token;

                    var contactClient = new RestClient();
                    contactClient.BaseUrl = "https://www.google.com/m8/feeds/contacts/default/full";

                    var contactRequest = new RestRequest(Method.GET);

                    contactRequest.RequestFormat = DataFormat.Json;

                    contactRequest.AddParameter("max-results", "9999");
                    contactRequest.AddParameter("sortorder", "ascending");
                    contactRequest.AddParameter("alt", "json");
                    contactRequest.AddParameter("access_token", access_token);
                    contactRequest.AddParameter("access_token_type", token_type);

                    var contactResponse = contactClient.Execute(contactRequest);
                    contactResponse.ContentType = "application/json";

                    if (contactResponse.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var json = contactResponse.Content;

                        JObject o = JObject.Parse(json);

                        //JsonConvert.DeserializeObject(o.SelectToken("$..entry"), (new JToken()).GetType());

                        foreach (var result in o.SelectToken("$..entry"))
                        {
                            Dictionary<string, string> emails = new Dictionary<string, string>();
                            Dictionary<string, string> phones = new Dictionary<string, string>();

                            var name = result["title"]["$t"].ToString();
                            var em = result["gd$email"];
                            var pn = result["gd$phoneNumber"];
                            var org = result["gd$organization"];
                            var note = result["gd$content"];
                            var workTitle = string.Empty;
                            var company = string.Empty;

                            try
                            {
                                // get emails
                                if (em != null && em.Any())
                                {
                                    if (em.Children().First()["rel"].ToString().Contains("#home"))
                                        emails.Add("home", em.Children().First()["address"].ToString());

                                    if (em.Children().First()["rel"].ToString().Contains("#work"))
                                        emails.Add("work", em.Children().First()["address"].ToString());

                                    if (em.Children().First()["rel"].ToString().Contains("#other"))
                                        emails.Add("other", em.Children().First()["address"].ToString());
                                }

                                // get phone numbers
                                if (pn != null && pn.Any())
                                {
                                    if (pn.Children().First()["rel"].ToString().Contains("#home"))
                                        phones.Add("home", pn.Children().First()["$t"].ToString());

                                    if (pn.Children().First()["rel"].ToString().Contains("#mobile"))
                                        phones.Add("mobile", pn.Children().First()["$t"].ToString());

                                    if (pn.Children().First()["rel"].ToString().Contains("#work"))
                                        phones.Add("work", pn.Children().First()["$t"].ToString());
                                }

                                // get organization details
                                if (org != null && org.Any())
                                {
                                    workTitle = org.Children().First()["gd$orgTitle"] != null ? org.Children().First()["gd$orgTitle"]["$t"].ToString() : "";
                                    company = org.Children().First()["gd$orgName"] != null ? org.Children().First()["gd$orgName"]["$t"].ToString() : null;
                                }

                                // get note
                                if (note != null && note.Any())
                                {
                                    note = note["$t"].ToString();
                                }

                                if (string.IsNullOrEmpty(name))
                                {
                                    if (emails.Count > 0)
                                        foreach (var item in emails)
                                        {
                                            name = item.Value;
                                        }
                                    else if (!string.IsNullOrEmpty(company))
                                        name = company;
                                    else
                                        name = null;
                                }
                            }
                            catch (Exception ex)
                            {
                                string error = ex.Message;
                                throw;
                            }

                            var contact = new Contacts();

                            contact.LastName = name;

                            foreach (var item in emails)
                            {
                                if (item.Key == "home")
                                    contact.EmailAddress = item.Value;

                                if (item.Key == "work")
                                    contact.EmailAddress2 = item.Value;

                                if (item.Key == "other")
                                    contact.EmailAddress2 = item.Value;
                            }

                            foreach (var item in phones)
                            {
                                if (item.Key == "home")
                                    contact.PhoneHome = item.Value;

                                if (item.Key == "work")
                                    contact.Phone = item.Value;

                                if (item.Key == "mobile")
                                    contact.Mobile = item.Value;
                            }

                            contact.Description = note != null ? note.ToString() : "";
                            contact.JobTitle = workTitle != null ? workTitle : "";

                            //var contact = new Contacts
                            //{
                            //    LastName = (!string.IsNullOrEmpty(result["title"]["$t"].ToString())) ? result["title"]["$t"].ToString() : "",
                            //    EmailAddress = result["gd$email"] != null ? (result["gd$email"].Any() ? result["gd$email"].Children().First()["address"].ToString() : "") : "",
                            //    Phone = result["gd$phoneNumber"] != null ? (result["gd$phoneNumber"].Any() ? result["gd$phoneNumber"].Children().First()["$t"].ToString() : "") : "0555"

                            //};

                            contactlist.Add(contact);
                        }
                    }
                }
            }

            return View(contactlist);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ImportContacts(FormCollection values)
        {
            for (int i = 0; i < (values.Count / 8); i++)
            {
                var firstname = string.Empty;
                var lastName = string.Empty;

                var fullname = values["name_" + i] != null ? values["name_" + i].Trim() : null;
                var email1 = values["email1_" + i] != null ? (values["email1_" + i].Length > 50 ? values["email1_" + i].Substring(0, 50).Trim() : values["email1_" + i].Trim()) : null;
                var email2 = values["email2_" + i] != null ? (values["email2_" + i].Length > 50 ? values["email2_" + i].Substring(0, 50).Trim() : values["email2_" + i].Trim()) : null;
                var phone = values["phone_" + i] != null ? values["phone_" + i].Trim() : null;
                var phoneHome = values["phoneHome_" + i] != null ? values["phoneHome_" + i].Trim() : null;
                var mobile = values["mobile_" + i] != null ? values["mobile_" + i].Trim() : null;
                var jobTitle = values["jobTitle_" + i] != null ? values["jobTitle_" + i].Trim() : null;
                var note = values["note_" + i] != null ? values["note_" + i].Trim() : null;

                if (!string.IsNullOrEmpty(fullname))
                {
                    var sp = fullname.Split(' ');
                    if (sp.Length > 0)
                    {
                        for (int j = 0; j < sp.Length; j++)
                        {
                            if (j == 0)
                                firstname = sp[j];
                            else
                                lastName += sp[j] + " ";
                        }
                    }
                    else
                    {
                        lastName = email1;
                    }
                }
                else
                {
                    lastName = email1;
                }

                var contact = new Contacts()
                {
                    AspNetUserId = Guid.NewGuid().ToString(),
                    LastName = lastName.Length > 50 ? lastName.Substring(0, 50) : lastName,
                    FirstName = firstname.Length > 50 ? firstname.Substring(0, 50) : firstname,
                    EmailAddress = email1,
                    EmailAddress2 = email2,
                    Phone = phone,
                    Mobile = mobile,
                    PhoneHome = phoneHome,
                    JobTitle = jobTitle,
                    Description = note,
                    Title = 1,
                    InsertedDate = DateTime.Now,
                    UpdatedDate = DateTime.Now,
                    IsDeleted = false
                };

                db.Contacts.Add(contact);
            }

            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw;
            }

            return View();
        }
    }
}

以上是关于csharp Google与restsharp和google api联系。的主要内容,如果未能解决你的问题,请参考以下文章

csharp RestSharp将JSON反序列化为动态

如何将 RestSharp 与 async/await 一起使用

C# RestSharp上传图片到Laravel API。

.NET Core - HttpClient 与 RestSharp [关闭]

WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择

这些是 RestSharp 和 ServiceStack 的客户端代码之间的主要区别吗? [关闭]