调用博客园 open api 的客户端示例代码

以下是调用博客园 open api 获取 access token 的客户端控制台程序示例代码,通过命令行参数传递 client id 与 client secret 。

C# 版

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace CSharpClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var clientId = args[0];
            var clientSecret = args[1];

            var host = new HostBuilder()
               .ConfigureServices((context, services) =>
               {
                   services.AddHttpClient();
               })
               .Build();

            using (var scope = host.Services.CreateScope())
            {
                var httpClient = scope.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient();

                var data = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["client_id"] = clientId,
                    ["client_secret"] = clientSecret,
                    ["grant_type"] = "client_credentials"
                });

                var response = await httpClient.PostAsync("https://api.cnblogs.com/token", data);
                Console.WriteLine(response.StatusCode);
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }
    }
}

Python 版

import sys
import requests

if __name__ == "__main__":
    clientId = sys.argv[1]
    clientSecret = sys.argv[2]

    response = requests.post("https://api.cnblogs.com/token", data={
        "client_id": clientId,
        "client_secret": clientSecret,
        "grant_type": "client_credentials"
    })

    print(response)
    print(response.content)
posted @ 2020-06-25 11:43  博客园团队  阅读(1248)  评论(0编辑  收藏  举报