连接到 MailChimp v3.0 API

Connection to MailChimp v3.0 API

我在连接到新的 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);
}

主要问题似乎是身份验证。这是一个很好的答案 .

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

并将其与这个问题的答案合并:

该示例使用简单的 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();
    }