跳至主要内容

C# 使用Blogger API V3 发布新博文


引用Google.Apis.Blogger.v3

新建个类 BloggerHelp

using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


   public class BloggerHelp
    {
        /// <summary>
        /// 憑證檔案路徑
        /// </summary>
        private string KeyFilePath = "C:\\auth2.json";

        /// <summary>
        /// 取得使用者資訊
        /// </summary>
        /// <returns></returns>
        public UserCredential GetCredential()
        {
            UserCredential credential;

            using (var stream = new FileStream(KeyFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { "https://www.googleapis.com/auth/blogger" },
                    "Kentilink",
                    CancellationToken.None,
                    new FileDataStore("Auth.Blogger")).Result;
            }

            return credential;
        }
    }

using Google.Apis.Blogger.v3;

using Google.Apis.Blogger.v3.Data;

using Google.Apis.Services;

BloggerHelp BloggerHelp = new BloggerHelp();
string blogUrl = "http://chinarednews.blogspot.com";
BloggerService BloggerService = new BloggerService(new BaseClientService.Initializer()
{
    HttpClientInitializer = BloggerHelp.GetCredential(),
    ApplicationName = "Test",
});
//取得Blogger資料
var BlogResource = BloggerService.Blogs.GetByUrl(blogUrl);
//第一次會請求允許
Blog blog = BlogResource.Execute();
Console.WriteLine("Blog ID: " + blog.Id);

//新增資料
Post PostData = new Post();

PostData.Content = Body;
//PostData.Labels = new List<string>() { "TestTag" };
PostData.Title = DateTime.Now.ToString() + " " + Title;

//執行新增
PostsResource PostsResource = new PostsResource(BloggerService);
PostsResource.Insert(PostData, blog.Id).Execute();

评论

此博客中的热门博文