4

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

2 回答 2

1

主要问题似乎是身份验证。这是一个很好的 SO 答案,它演示了 HTTP Basic Auth withHTTPWebRequest .

于 2016-01-26T20:31:21.420 回答
0

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

并将其与此问题的答案合并在一起: Calling MailChimp API v3.0 with .Net

该示例使用一个简单的 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();
    }
于 2016-12-06T15:09:47.500 回答