Connection to MailChimp v3.0 API

本文关键字:API v3 MailChimp to Connection | 更新日期: 2023-09-27 18:31:49

我在连接到新的MailChimp 3.0 API时遇到问题(2.0工作正常)。

我想发送一些订阅者。我做错了什么?我可能试图以错误的方式发送apikey(HTTP 基本身份验证)。文档在这里,但我无法使其工作:http://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://us12.api.mailchimp.com/3.0/lists/<listnumber>/members/");
string json = @"
    {
        ""email_address"": ""test@test.com"",
        ""status"": ""subscribed"",
        ""merge_fields"": {
                    ""FNAME"": ""Urist"",
            ""LNAME"": ""McVankab""
        }
    }
";
byte[] data = Encoding.UTF8.GetBytes(json);
request.Method = "POST";
request.Headers.Add("user", "<mykeynumber>");
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (System.IO.Stream stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

Connection to MailChimp v3.0 API

主要问题似乎是身份验证。这是一个很好的SO答案,它演示了带有HTTPWebRequest的HTTP基本身份验证。

其他任何人来到这里,我一直在玩,我认为此时最好使用 ASP.NET Web API 库调用它。 我按照这个例子让它工作:https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

并将其与这个问题的答案合并在一起:使用 .Net 调用 MailChimp API v3.0

该示例使用简单的 Windows 控制台应用,但可以移植到 Web:

// New code:
    static HttpClient client = new HttpClient();
    static void Main()
    {
        RunAsync().Wait();
    }
    static async Task RunAsync()
    {
        // New code:
        client.BaseAddress = new Uri( "https://us5.api.mailchimp.com/3.0/" );
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue( "application/json" ) );
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", "<YOUR_API_KEY_HERE>" );
        try {
            HttpResponseMessage response = await client.GetAsync( "" );
            if ( response.IsSuccessStatusCode ) {
                var results = await response.Content.ReadAsStringAsync();
                Console.WriteLine( $"results  (HTTP Status = {results})" );
            }
            else {
                Console.WriteLine( $"ERROR (HTTP Status = {response.StatusCode}" );
            }

        }
        catch ( Exception e ) {
            Console.WriteLine( e.Message );
        }
        Console.ReadLine();
    }