본문 바로가기
프로그래밍 언어/C#

[C#] 구글 블로거 API로 글 등록하는 법

by 연구자 공학코드 2020. 12. 23.

공지사항

  1. 제가 운영하는 네이버 카페 개발자 커뮤니티 코어큐브(https://cafe.naver.com/ewsncube)에 가입하시면 컴퓨터 관련 학습 자료와 질의응답을 제공받으실 수 있습니다.

728x90
반응형

한국을 소개하는 영어 블로그를 운영하려고 하는데 글을 편하게 쓰기 위하여 구글 블로거 API로 글을 등록하는 예제 프로그램을 작성해보았다.

 

글 등록 예제 소스코드

using System;
using System.IO;
using Google.Apis.Blogger.v3.Data;
using Google.Apis.Blogger.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using System.Threading;
using System.Threading.Tasks;

namespace InsertPost
{
    class InsertPost
    {
        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            try
            {
                MainAsync(args, cts.Token).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine("EXCEPTION: " + e.Message);
                }
            }
        }

        static async Task MainAsync(string[] args, CancellationToken ct)
        {
            // Google OAuth 2.0 자격증명
            UserCredential credential;

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

            // 구글 블로거 서비스 초기화
            BloggerService service = new BloggerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
            });           

            string blogId = "blodId";
            Post insertPost = new Post();

            insertPost.Title = "제목입니다";
            insertPost.Content = "<p>HTML콘텐츠를 여기에다가 넣으면 됩니다.</p>";

            // 구글 블로거 글 등록
            await service.Posts.Insert(insertPost, blogId).ExecuteAsync(ct);
        }
    }
}

구글 블로거에 글을 등록하기 위해서는 구글 OAuth 2.0으로 사용자 인증을 먼저해야한다. 해당 인증 후에는 구글 블로거 서비스를 시작하고 필요에 따라 구글 블로거 서비의 기능을 이용하면 된다. 위의 소스로 실행파일을 생성하면 실행파일과 같은 경로에 다음의 파일을 생성하여 인증 정보를 입력하도록 한다.

 

client_secret_oauth.json

{
  "installed": {
    "client_id": "client_id",
    "client_secret": "client_secret",
    "redirect_uris": [ "http://localhost", "urn:ietf:wg:oauth:2.0:oob" ],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

구글 클라우드 플랫폼에서 생성한 OAuth 2.0 인증 정보를 위의 .json 파일에 입력한다. 인증 정보 생성은 참고자료[5]에 나타나 있다.

 

글 등록 프로그램을 실행한 화면
글이 등록된 화면

구글 블로거 관리자 화면에서 글이 잘 등록됬는지를 확인할 수 있다.

 

참고자료

[1] How to use Blogger API v3, stackoverflow, 2013-10-08.

[2] C# Google API Blogger 예제, bit Syrup, 2019-08-13.

[3] Client Secrets, Google API Client Libraries, 2014-03-12.

[4] Google Blogger API .Net(googleapis.dev/dotnet/Google.Apis.Blogger.v3/latest/api/Google.Apis.Blogger.v3.html)

[5] [C#] 구글 블로거 API - 블로그 정보를 읽어오자, 공학코드, 2020-12-09

 

 

 

728x90
반응형

댓글